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

使用Nginx+Gunicorn部署Django时静态文件路径错误无法加载如何解决

问题根因

你遇到的静态文件路径多了一层/static/的问题,核心是两类原因:要么是前端模板的静态资源引用路径写错,要么是Nginx的静态资源匹配规则未生效、静态目录配置冲突。

排查解决步骤

  • 首先检查模板里的静态资源引用方式
    不要硬编码/static/前缀的路径,也不要在{% static %}标签里重复写/static/,正确写法是:

    <!-- 正确写法 -->
    <script src="{% static 'rest_framework/js/default.js' %}"></script>
    <!-- 错误写法(会生成 /static/static/rest_framework/... 路径) -->
    <script src="{% static '/static/rest_framework/js/default.js' %}"></script>
    <script src="/static/static/rest_framework/js/default.js"></script>
    
  • 修正Nginx配置,确保静态路径匹配优先级
    给/static/和/media/的location规则加^~修饰符,避免被其他后缀类正则匹配规则覆盖,修改后的配置如下:

    server {
        listen 80;
    
        location ^~ /static/ {
            alias /home/x/aroundu/core/core/static/;
        }
    
        location ^~ /media/ {
            alias /home/x/aroundu/core/media/;
        }
    
        location / {
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn.sock;
        }
    }
    

    修改完成后执行命令验证配置正确性并重载Nginx:

    sudo nginx -t && sudo nginx -s reload
    
  • 验证Django静态配置和静态文件收集结果

    1. 进入项目目录执行Django shell确认BASE_DIR路径:
    python manage.py shell
    

    输入以下代码打印配置:

    from django.conf import settings
    print("BASE_DIR:", settings.BASE_DIR)
    print("STATIC_ROOT:", settings.STATIC_ROOT)
    

    确认STATIC_ROOT输出为/home/x/aroundu/core/core/static,如果路径不对调整settings里的STATIC_ROOT配置即可。
    2. 重新收集静态文件,确保rest_framework等第三方包的静态文件都被正确归集:

    python manage.py collectstatic --noinput
    
  • 额外排查项
    如果server块里配置了全局root参数,注意不要和alias规则冲突,全局root不要指定到/home/x/aroundu/core/core/层级下,避免未匹配到location时拼接出错误路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:27:03