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

Django搭配nginx+gunicorn认证失效但runserver运行正常问题求助

修复步骤

1. 修改Nginx配置

在你的Nginx配置location /段中补充以下头信息配置,保留原有配置不变:

location / {
    # 新增配置
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Cache-Control "no-cache, no-store, must-revalidate";
    proxy_set_header Pragma "no-cache";

    # 原有配置
    proxy_redirect off;
    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_read_timeout 300;
    proxy_pass http://django:8050;
}

修改完成后重启Nginx容器生效。

2. 补充Django settings.py配置

在你的settings.py中添加以下配置项:

# 信任反向代理传递的Host头和协议头
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# 允许站点域名访问,生产环境请替换为实际使用的域名
ALLOWED_HOSTS = ["*"]

# 若当前使用HTTP协议访问站点,需关闭安全Cookie限制,HTTPS环境可设为True
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False

# 确认session存储为共享的数据库模式(默认配置,未手动修改过可省略)
SESSION_ENGINE = "django.contrib.sessions.backends.db"

修改完成后重启Django容器生效。

3. 可选验证步骤

如果修改后仍存在问题,可先将gunicorn worker数临时改为1验证是否为多worker会话同步问题:

exec gunicorn DataManagement.wsgi:application \
    --name=DataManagement \
    --workers=1 \
    --log-level=debug \
    --bind=0.0.0.0:8050 \
    --timeout=600 \
    --log-file=./gunicorn.log

如果worker设为1后问题消失,说明你的session存储实际未使用共享存储(比如误配置为本地内存缓存),改回数据库或Redis等共享存储即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:24:04