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

同一域名下前后端不同端口配置问题求助(Django+Nginx)

Django + Nginx部署问题:域名+8000无法访问后端,IP+8000正常

问题详情

我是Django和Nginx新手,部署应用时碰到了麻烦:前端通过example.com:80能正常访问,但后端用example.com:8000打不开,换成服务器IP加8000端口却能正常访问。已经折腾两天没解决,求帮忙。

现有Nginx配置

前端配置

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

include snippets/snakeoil.conf;
server_name example.com;

location = /favicon.ico { access_log off; log_not_found off; }

location / {
            # reverse proxy for next server
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_headers_hash_max_size 512;
            proxy_headers_hash_bucket_size 128;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }

 }

后端配置

server {
    listen 8000;
    server_name example.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
            root /root/backend/lithexBackEnd;
    }
    location / {
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn.sock;
    }
}

排查和解决方法

  • 检查端口放行:服务器的安全组/防火墙必须开放8000端口。如果用UFW,执行ufw allow 8000/tcp,然后ufw reload;用iptables的话,加iptables -A INPUT -p tcp --dport 8000 -j ACCEPT,保存规则后重启防火墙。
  • 修正Nginx后端监听配置:把后端配置里的listen 8000;改成listen 8000 default_server;,确保Nginx能正确匹配example.com:8000的请求,不会因为主机名匹配问题忽略这个server块。
  • 验证域名解析:确认example.com的A记录完全指向你的服务器IP,没有CDN缓存或解析错误。可以用nslookup example.com在本地测试解析结果。
  • 检查Django允许的主机:在Django的settings.py里确认ALLOWED_HOSTS列表包含example.com,避免因为主机名不被信任而拒绝请求。
  • 查看日志定位问题:
    • 查看Nginx错误日志:tail -f /var/log/nginx/error.log,找请求被拒绝或无法转发的记录
    • 查看Gunicorn日志,确认是否收到了来自example.com的请求,以及是否有异常报错
  • 验证Nginx配置并重启:执行nginx -t确保配置无语法错误,没问题就重启Nginx:systemctl restart nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:30:43