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

生产环境Nginx服务器下Django静态资源加载异常求助

Django+Nginx部署静态资源加载问题修复

问题根源

不带端口访问域名时,请求通过Nginx代理,但Nginx的静态资源配置存在异常;带端口访问时,请求直接抵达后端服务(如gunicorn或Django开发服务器),后端自行处理静态资源请求,因此能正常加载。

修复步骤

1. 确认Django静态文件配置与收集

  • 检查settings.py中的静态资源配置,确保路径正确:
    STATIC_URL = '/static/'
    STATIC_ROOT = '/home/ubuntu/santhals/myapp/static/'
    
  • 执行静态文件收集命令,将所有app的静态文件统一复制到STATIC_ROOT目录:
    python manage.py collectstatic
    

2. 调整Nginx静态资源配置

当前Nginx的/static/ location配置可能存在路径匹配或权限问题,修改为以下配置:

server {
    listen 80;
    server_name santhals.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    
    location /static/ {
        root /home/ubuntu/santhals/myapp/;
        # 禁止目录索引,添加缓存优化
        autoindex off;
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

如果你的STATIC_ROOT实际路径是/home/ubuntu/santhals/static/(而非项目目录下的static),则改用alias配置更准确:

location /static/ {
    alias /home/ubuntu/santhals/static/;
    autoindex off;
    expires 30d;
    add_header Cache-Control "public, max-age=2592000";
}

3. 修复静态文件目录权限

确保Nginx运行用户(默认是www-data)拥有静态文件目录的读取权限:

sudo chown -R www-data:www-data /home/ubuntu/santhals/myapp/static/
sudo chmod -R 755 /home/ubuntu/santhals/myapp/static/

4. 重启Nginx并验证

  • 检查Nginx配置是否合法:
    sudo nginx -t
    
  • 重启Nginx服务:
    sudo systemctl restart nginx
    
  • 若仍有问题,查看Nginx错误日志排查细节:
    sudo tail -f /var/log/nginx/error.log
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:33:32