关于Linux使用Nginx部署静态网站跳转403问题。

今天通过sudo yum install nginx 在Anolis安装Nginx,一切很顺利。然后修改配置文件增加项目配置,在/etc/nginx/nginx.conf文件添加如下内容:

server {
    	listen   8000;
        server_name  localhost;

		location / {            
            try_files $uri $uri/ /index.html;
            root /home/app/dist;
            index index.html index.htm;
        }

        location /api/ {
			proxy_set_header Host $http_host;
      	    proxy_set_header X-Real-IP $remote_addr;
      	    proxy_set_header REMOTE-HOST $remote_addr;
      	    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

      	    # websocket
      	    proxy_http_version 1.1;
      	    proxy_set_header Upgrade $http_upgrade;
      	    proxy_set_header Connection "upgrade";
      	    proxy_pass http://127.0.0.1:8080;
      	}

        #  error_page   500 502 503 504  /50x.html;

        location = /50x.html {
            root 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

通过 sudo systemctl reload nginx 重新加载nginx配置文件,通过 curl 访问网站时请求被重定向到403错误页。通过日志排查发现 *10 "/home/dist/index.html" is forbidden (13: Permission denied), 不拉不拉不拉......,这就很清晰了,大概意思是Nginx没有权限访问 /home/dist/index.html 文件,通常是文件或目录权限或SELinux 安全策略导致。

解决办法:

1. 检查并修复目录或文件权限  

  1. 确认nginx运行用户,通过 grep "user" /etc/nginx/nginx.conf,通常输出 user nginx,标识Niginx以nignx用户运行;
  2. 重新指定目录或文件所有者,将项目文件所有者改为nignx,命令:sudo chown -R nginx:nginx /home/dist;
  3. 设置正确的权限,确保有执行(x)和读取权限(r)
    # 递归设置目录权限为 755(所有者可读写执行,其他用户可读可执行)
    sudo chmod -R 755 /usr/share/nginx/dist
    # 单独确保 index.html 有读取权限
    sudo chmod 644 /usr/share/nginx/dist/index.html

2. 确认SELinux安全策略

通畅Anolis默认开启SELinux,会限制Nginx访问非标准目录(/home/dist不在默认允许路径)。

临时解决办法:sudo setenforce 0  #临时关闭,重启后恢复默认状态,若手动恢复,将0改为1执行。

永久解决办法:

  1. 为 dist 目录及子文件设置允许httpd访问的上下文
    sudo chcon -R -t httpd_sys_content_t /home/dist
  2. 如果允许nginx写入目录,需额外添加:
    sudo chcon -R -t httpd_sys_rw_content_t /home/dist

3. 最后验证是否正常

  1. 检查配置文件是否正确,指令:sudo nginx -t
  2. 重新加载 nginx 配置,指令:sudo systemctl reload nginx
  3. 访问网站首页,通过curl指令。

 

posted @ 2025-08-22 10:01  七月的枫丶  阅读(20)  评论(0)    收藏  举报