403 Forbidden 只是一个HTTP状态码,像404,200一样不是技术上的错误。 哪些场景需要返回403状态码的场景? 1.网站禁止特定的用户访问所有内容,例:网站屏蔽某个ip访问。 2.访问禁止目录浏览的目录,例:设置autoindex off后访问目录。 3.用户访问只能被内网访问的文件。 以上几种常见的需要返回 403 Forbidden 的场景。 (1) nginx配置文件里没有配置默认首页参数 [root@mobana conf]# cat extra/www.conf server { listen 80; server_name www.klaus.org; location / { root html/www; #index index.html index.htm; 首页文件没有生效 } } [root@mobana conf]# tail -l /etc/hosts 10.168.168.62 www.klaus.org bbs.klaus.org bolg.klaus.org [root@mobana conf]# ll ../html/www/ -rw-r--r-- 1 root root 21 125 16:41 index.html 首页文件存在 [root@mobana conf]# curl -I -s 10.168.168.62|head-1HTTP
/1
.1 403 Forbidden
N
ginx没有指定首页文件的参数,因此访问Nginx时不会把index.html当首页,所以报403错误。
(2)站点目录下没有配置文件里指定的首页文件 [root@mobana conf]# cat extra/www.conf server { listen 80; server_name www.klaus.org; location / { root html/www; index index.html index.htm; 首页文件生效 } } [root@mobana conf]# tail -l /etc/hosts 10.168.168.62 www.klaus.org bbs.klaus.org bolg.klaus.org [root@mobana conf]# ll ../html/www/ 首页文件不存在 [root@mobana conf]# curl -I -s 10.168.168.62|head-1
HTTP
/1
.1 403 Forbidden
N
ginx没有找到首页目录下的首页文件,所以报403错误。
(3)站点目录或内部的程序文件没有Nginx用户访问权限。 [root@mobana conf]# ll ../html/www/index.html -rwxr----- 1 root root 21 125 16:41 ../html/www/index.html [root@mobana conf]#curl -I -s 10.0.0.8|head -1HTTP
/1
.1 403 Forbidden
403错误
[root@mobana conf]# chmod 755 ../html/www/index.html [root@mobana conf]# ll ../html/www/index.html -rwxr-xr-x 1 root root 21 125 16:41 ../html/www/index.html [root@mobana conf]#curl -I -s 10.0.0.8|head -1 HTTP/1.1 200 OK #<==200 OK了 (4) Nginx配置文件中设置allow、deny等权限控制,导致客户端没有没权限访问。 [root@mobana conf]# cat extra/www.conf server { listen 80; server_name www.klaus.org; location / { root html/www; index index.html index.htm; 首页文件生效
allow 192.168.0.0/24;
deny all;
} } [root@mobana conf]# curl -I -s 10.168.168.62|head -1 HTTP/1.1 200 OK. [root@mobana conf]# ../sbin/nginx -s reload [root@mobana conf]# curl -I -s 10.168.168.62|head -1 HTTP/1.1 403 Forbidden