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

按推荐方案配置后Nginx仍无法为Django项目提供静态文件服务

问题排查与修复方案

错误点1:Nginx location 匹配规则错误

你当前配置的location = /static是精确匹配规则,仅能匹配URI完全等于/static的请求,所有/static/xxx形式的静态资源请求都无法命中该规则,会直接转发给Django处理,自然返回404。

错误点2:静态资源路径映射逻辑错误

你当前的静态资源URL是/static/findings/styles/base.css,若按照你现有alias配置,命中规则后拼接出的实际本地路径为/home/django/static/findings/findings/styles/base.css,多了一层findings目录,Nginx无法找到对应文件。

前置检查项

  • 确认你已经执行过python manage.py collectstatic命令,所有静态文件已经正确同步到/home/django/static/findings/目录下
  • 确认/home/django/目录对www-data用户有执行权限(进入目录需要执行权限),可执行chmod o+x /home/django临时验证

修复后Nginx配置

server {
  listen 80;

  location = /favicon.ico {
    access_log off;
    log_not_found off;
  }
  # 改用前缀匹配,优先级高于普通正则,所有/static开头的请求都命中该规则
  location ^~ /static/ {
    autoindex on;
    # 调整alias路径,确保路径拼接正确
    alias /home/django/static/;
  }
  location / {
        include proxy_params;
        proxy_pass http://unix:/home/django/findings-app/run/findings.sock;
  }
}

生效操作

  • 执行nginx -t测试配置语法是否正确
  • 执行systemctl reload nginx重载配置即可生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:45:04