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

Nginx反向代理异常:后端接口交替出现404求助排查

问题诊断与解决方案

核心问题分析

交替出现404与正常加载的循环问题,根源在于Nginx配置中的Host请求头错误设置,以及冗余的端口配置:

  1. 错误的Host头格式:proxy_set_header Host $host/; 末尾多了斜杠,导致Django收到的Host头为abc123.com:/或abc123.com:8000/。Django的路由系统会因Host不匹配(ALLOWED_HOSTS未包含带斜杠的域名)返回404;部分场景下可能因请求处理逻辑绕过检查,导致正常加载,形成循环。
  2. 冗余的server_name端口:server_name abc123.com:8000 www.abc123.com:8000; 无需在server_name中指定端口,Nginx通过listen指令的8000端口匹配请求,server_name仅需填写域名即可。
  3. 未使用WSGI服务器:直接运行Django开发服务器(而非Gunicorn/uWSGI)本身不适合生产环境,其单线程/简易多进程模式可能加剧请求处理的不稳定。

修正后的Nginx配置

server {
    listen       80;
    listen       [::]:80;

    server_name  abc123.com www.abc123.com;

    root        /var/www/test.abc.com/build;
    access_log /var/log/nginx/test_80/access.log main buffer=16k; # 修正原路径空格错误
    error_log  /var/log/nginx/test_80/error.log notice;

    error_page 404 /404.html;
    location = /404.html {}

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {}
}

server{
    listen 8000;
    listen [::]:8000;

    server_name  abc123.com www.abc123.com; # 移除端口后缀
    root   /app/abc-Backend/;
    access_log  /var/log/nginx/test_8000/access.log;
    error_log /var/log/nginx/test_8000/error.log notice;

    location / {
        proxy_pass  http://localhost:8001/;
        proxy_redirect http://localhost:8001/ $scheme://$host:8000/;
        proxy_set_header Host $host; # 移除末尾多余斜杠
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 排查阶段可暂时注释缓存配置,确认问题解决后再启用
        # proxy_cache my_cache;
        # proxy_cache_valid 200 304 10m;
        # proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        
        add_header "Access-Control-Allow-Origin" *;
        add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS";
        add_header "Access-Control-Allow-Headers" "Authorization";
    }
}

额外必要配置

  1. Django ALLOWED_HOSTS设置:确保settings.py中包含正确的域名:
ALLOWED_HOSTS = ['abc123.com', 'www.abc123.com']
  1. 启用WSGI服务器:尽快切换到Gunicorn或uWSGI运行Django,示例Gunicorn启动命令:
gunicorn --bind 127.0.0.1:8001 your_project.wsgi:application

验证步骤

  1. 重启Nginx服务:systemctl restart nginx
  2. 检查Django日志,确认是否还有Host头相关的错误提示
  3. 多次访问后端路径,确认404循环问题是否解决

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:53:10