Django+Nginx+Gunicorn非根页面404问题求助
当尝试访问非根页面(如/user/)时,Nginx返回404错误,错误日志提示"/usr/share/nginx/html/user/login/index.html"未找到。
当前使用的Nginx配置如下:
server { listen 80; server_name ip_address; location = /static { root /opt/scrumban/kanbanboard/; autoindex off; } location = / { include proxy_params; proxy_pass http://unix:/opt/scrumban/kanbanboard/kanban.sock; } }
嘿,我来帮你搞定这个Nginx的404问题~你的核心问题在于当前配置只精确匹配了根路径/,其他所有非根路径(比如/user/)都没有对应的处理规则,所以Nginx会默认去它的默认静态文件目录/usr/share/nginx/html/找对应的页面,自然就找不到报错了。
这里给你两个实用的修复方案,你可以根据自己的需求选择:
方案1:全局转发所有非静态请求(推荐)
如果你的后端服务需要处理除了/static之外的所有请求,直接把精确匹配的location = /改成匹配所有路径的location /就行。因为精确匹配=的优先级更高,所以/static的规则依然会优先生效:
server { listen 80; server_name ip_address; # 处理静态文件请求 location = /static { root /opt/scrumban/kanbanboard/; autoindex off; } # 所有其他请求都转发到后端服务 location / { include proxy_params; proxy_pass http://unix:/opt/scrumban/kanbanboard/kanban.sock; } }
⚠️ 小提醒:如果你的静态文件实际存放在/opt/scrumban/kanbanboard/static/目录下,那可能需要把location = /static改成location /static(去掉=),这样请求/static/css/main.css就会对应到/opt/scrumban/kanbanboard/static/css/main.css,你可以根据自己的文件结构调整。
方案2:针对特定路径单独配置
如果只有部分非根路径需要转发(比如只有/user/开头的路径),可以单独添加对应的location规则:
server { listen 80; server_name ip_address; location = /static { root /opt/scrumban/kanbanboard/; autoindex off; } location = / { include proxy_params; proxy_pass http://unix:/opt/scrumban/kanbanboard/kanban.sock; } # 专门处理/user/开头的所有请求 location /user/ { include proxy_params; proxy_pass http://unix:/opt/scrumban/kanbanboard/kanban.sock; } }
不过这种方式扩展性不强,如果后续有更多路径需要转发,还是方案1更省心。
最后一步:生效配置
修改完配置后,先执行nginx -t检查配置是否合法,确认没问题后再执行systemctl reload nginx让新配置生效就可以啦~
内容的提问来源于stack exchange,提问作者Philip White

