You need to enable JavaScript to run this app. Nginx搭配Django+Gunicorn部署时静态文件加载返回404错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Nginx搭配Django+Gunicorn部署时静态文件加载返回404错误求助

Nginx静态文件404问题解决方案
  • 修正站点匹配规则
    你当前配置的server_name仅包含localhost、127.0.0.1,但实际访问域名为example.com,请求无法匹配到该server块,会触发默认站点规则导致404。修改配置如下:
    server {
          listen 80;
          # 新增你实际访问的域名
          server_name localhost 127.0.0.1 example.com;
    
          location = /favicon.ico { access_log off; log_not_found off; }
          location /static {
                  autoindex on;
                  alias /home/ngx/pid/static/;
          }
    
          location / {
                  include proxy_params;
                  proxy_pass http://unix:/run/gunicorn.sock;
          }
    

}

- 确认配置生效
依次执行以下命令:
```bash
# 验证Nginx配置语法是否正确
nginx -t
# 确保sites-available下的配置已软链到sites-enabled目录,替换为你的实际配置文件名
ln -sf /etc/nginx/sites-available/<你的配置文件名> /etc/nginx/sites-enabled/
# 重载Nginx使配置生效
systemctl reload nginx
  • 修复目录权限问题
    Nginx默认运行用户为www-data,需确保静态资源所有上级目录对该用户有读取+执行权限:
    chmod o+rx /home/ngx
    chmod o+rx /home/ngx/pid
    chmod -R o+r /home/ngx/pid/static
    find /home/ngx/pid/static -type d -exec chmod o+x {} \;
    
    也可直接修改/etc/nginx/nginx.conf首行的运行用户为user ngx;,修改后重载Nginx即可。
  • 核对Django静态配置
    检查diary/settings.py中的静态规则:
    STATIC_URL = '/static/'
    STATIC_ROOT = '/home/ngx/pid/static/'
    # 新增React打包目录到静态文件扫描路径,替换为你实际的React打包输出目录
    STATICFILES_DIRS = [
        "/home/ngx/pid/frontend/build",
    ]
    
    配置修改后重新执行静态收集:
    cd /home/ngx/pid
    source djenv/bin/activate
    python manage.py collectstatic
    
    执行完成后手动验证/home/ngx/pid/static/frontend/main.js、/home/ngx/pid/static/css/index.css文件是否真实存在。
  • 静态规则优化(可选)
    如果上述步骤执行后仍有问题,可将alias写法替换为root写法验证:
    location /static/ {
        autoindex on;
        root /home/ngx/pid/;
    }
    

内容的提问来源于stack exchange,提问作者IQ.tree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 06:45:04