0%

Nginx 403 Forbidden

每次重新部署 Nginx 总会遇到 Nginx 403 Forbidden 这个错误,这里列一个排除此类错误的清单。

  1. 确认 Nginx 正常启动,这里要记录启动 Nginx 的用户供后续步骤使用,通常是 nginx

    $ ps -ef | grep nginx | grep -v grep

    root 1714 1 0 14:27 ? 00:00:00 nginx: master process /usr/sbin/nginx
    nginx 1973 1714 0 14:45 ? 00:00:00 nginx: worker process
  2. 确认 Nginx 的初始配置 /etc/nginx/nginx.conf 正确,特别注意 rootindex

    $ cat /etc/nginx/nginx.conf

    ...
    server {
    listen 80;
    listen [::]:80;
    server_name _;
    root /srv/zhongyiio/;

    location / {
    index index.html;
    }
    }
    ...

    $ sudo nginx -t # 如果不是以下结果,需要根据报错修改语法错误

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
  3. 确认网站静态目录权限,一般情况文件夹 755、文件 644 就行,用户和用户组和步骤 1 保持一致,这里为 nginx。

    $ ls -la /srv/zhongyiio

    total 44
    drwxr-xr-x. 11 nginx nginx 235 Nov 13 08:27 .
    drwxr-xr-x. 3 root root 23 Nov 14 14:14 ..
    drw-r--r--. 5 nginx nginx 36 Nov 13 08:27 2017
    -rw-r--r--. 1 nginx nginx 10 Nov 13 08:27 CNAME
    drw-r--r--. 3 nginx nginx 36 Nov 13 08:27 archives
    -rw-r--r--. 1 nginx nginx 18197 Nov 13 08:27 atom.xml
    -rw-r--r--. 1 nginx nginx 1785 Nov 13 08:27 baidusitemap.xml
    drw-r--r--. 4 nginx nginx 32 Nov 13 08:27 categories
    drw-r--r--. 2 nginx nginx 44 Nov 13 08:27 css
    -rw-r--r--. 1 nginx nginx 1150 Nov 13 08:27 favicon.ico
    drw-r--r--. 2 nginx nginx 70 Nov 13 08:27 img
    -rw-r--r--. 1 nginx nginx 5164 Nov 13 08:27 index.html
    drw-r--r--. 2 nginx nginx 23 Nov 13 08:27 js
    drw-r--r--. 2 nginx nginx 24 Nov 13 08:27 reading
    -rw-r--r--. 1 nginx nginx 922 Nov 13 08:27 sitemap.xml
    drw-r--r--. 3 nginx nginx 23 Nov 13 08:27 tags
    drw-r--r--. 2 nginx nginx 24 Nov 13 08:27 talking
  4. 确认 SELinux 是否开启,不建议关闭 SELinux

    $ sestatus

    SELinux status: enabled
    SELinuxfs mount: /sys/fs/selinux
    SELinux root directory: /etc/selinux
    Loaded policy name: targeted
    Current mode: enforcing
    Mode from config file: enforcing
    Policy MLS status: enabled
    Policy deny_unknown status: allowed
    Max kernel policy version: 28

    # 如果状态为 enabled 使用该命令,确保之后建立的文件和复制的文件具有
    # 相同 httpd_sys_content_t 的类型,从而使受限的 httpd 进程能够访问
    $ sudo chcon -R -t httpd_sys_content_t /srv/zhongyiio/