You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS EC2实例中Nginx返回403 Forbidden问题排查求助

解决Nginx 403 Forbidden错误的步骤

1. 修复React静态文件缺失问题

本地运行React依赖开发服务器,但部署生产环境必须先构建静态资源:

  • 进入React项目目录:cd /home/ubuntu/apps/myapp-frontend
  • 安装依赖(未安装时执行):npm install
  • 执行生产构建:npm run build
    构建完成后会生成build目录,里面包含index.html和所有编译后的静态文件

修改Nginx站点配置,将根目录指向build文件夹,同时调整单页应用的路由规则:

server {
        listen 80;
        listen [::]:80;
        # 指向React构建后的静态目录
        root /home/ubuntu/apps/myapp-frontend/build;
        index index.html index.htm index.nginx-debian.html;
        server_name website.ip.address;
        location / {
                # React单页应用需用此规则避免刷新路由404
                try_files $uri $uri/ /index.html;
        }
        location /api {
            proxy_pass http://localhost:8080;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
}

2. 修复目录权限链问题

即使文件所有者为ubuntu:ubuntu,目录链缺失执行权限会导致Nginx无法访问:

  • 检查并调整上级目录权限:
    # 确保/home/ubuntu目录允许用户进入
    sudo chmod 755 /home/ubuntu
    # 调整apps和项目目录权限
    sudo chmod 755 /home/ubuntu/apps
    sudo chmod 755 /home/ubuntu/apps/myapp-frontend
    # 确保build目录下文件可读、目录可进入
    sudo chmod -R 755 /home/ubuntu/apps/myapp-frontend/build
    

3. 验证配置并重启Nginx

  • 测试Nginx配置合法性:sudo nginx -t
  • 配置正确后重启服务:sudo systemctl restart nginx

额外检查点

  • 确认Node.js后端正常运行在8080端口:执行curl http://localhost:8080/api/你的接口路径,验证能返回正常数据
  • 检查EC2安全组是否开放80端口,允许外部IP访问

内容的提问来源于stack exchange,提问作者djokerndthief

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:05:19