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

部署到Nginx的Django服务器无法接收Cookie问题排查

问题描述

使用配置了withCredentials: true的Axios或Postman向部署在Nginx服务器上的Django应用发送POST请求时,无法在应用中访问Cookie(Cookie未被发送)。本地环境下相同配置可正常运行,部署后出现问题。

Axios配置:

export function genericApiHost(host: string) {
  const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    // "Access-Control-Allow-Origin": true,
  };
  return axios.create({
    baseURL: `${host}`,
    headers: headers,
    withCredentials: true,
  });
}

手动添加Access-Control-Allow-Origin请求头会触发CORS错误,不添加则Cookie无法发送。

Django配置:

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_TRUSTED_ORIGINS = ['*']
ALLOWED_HOSTS = ["*"]
解决方案

问题核心是Nginx反向代理未正确处理CORS头和Cookie传递,本地无Nginx转发所以配置生效,部署后需调整Nginx配置:

  1. 配置Nginx动态CORS响应头
    当CORS_ALLOW_CREDENTIALS = True时,Access-Control-Allow-Origin不能是*,必须匹配请求的具体Origin。在Nginx的location块中添加:
location / {
    proxy_pass http://your-django-upstream; # 替换为你的Django服务地址

    # 处理OPTIONS预检请求
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "Content-Type, Accept, X-CSRFToken";
        add_header Access-Control-Allow-Credentials "true";
        return 204;
    }

    # 为非OPTIONS请求添加CORS头
    add_header Access-Control-Allow-Origin $http_origin;
    add_header Access-Control-Allow-Credentials "true";
}

用$http_origin动态匹配请求来源,避免固定*导致的Credentials兼容问题。

  1. 确保Nginx传递Cookie相关头
    反向代理时需配置proxy_set_header,保证Cookie能正确在客户端和Django之间传递:
location / {
    proxy_pass http://your-django-upstream;
    # 传递必要的请求头
    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;
    # 传递客户端Cookie到Django
    proxy_set_header Cookie $http_cookie;
}
  1. 调整Django的Cookie安全配置(可选)
    如果服务器使用HTTPS,需将CSRF_COOKIE_SECURE和SESSION_COOKIE_SECURE设为True,确保Cookie仅通过HTTPS传输;HTTP环境保持False即可,但生产环境建议启用HTTPS。

  2. Postman测试要点
    在Postman中,进入Settings -> Cookies,确保开启Send cookies,且请求URL与Cookie的Domain一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:07:08