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

Nginx未向gunicorn socket传递认证信息的配置问题求解

问题原因

你遇到的问题由两个常见配置问题共同导致:

  • 你在server块全局配置了auth_basic基础认证,Nginx处理完Basic认证逻辑后,默认会清空客户端携带的Authorization请求头,不会传递给上游的Gunicorn服务,导致你的JWT令牌根本没有传到后端服务
  • 你用的默认proxy_params没有显式配置透传Authorization头,就算没有auth_basic的冲突,也有可能出现头字段透传失败的情况

解决方案

方法1:取消全局auth_basic(推荐)

如果只有部分后台路径需要Basic认证,不要在server全局加auth_basic配置,将这部分配置移到对应需要认证的location块中即可,接口路径不需要Basic认证的话,Authorization头就不会被Nginx清空。
修改后的配置参考:

server {
      listen 80;
      server_name dev.website.com;

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

      location /static {
             alias /home/ubuntu/platform/backend/static;
      }

      # 将auth_basic配置移到需要的路径下,比如后台管理路径
      # location /admin {
      #        auth_basic "Admin Login";
      #        auth_basic_user_file /etc/nginx/.htpasswd;
      #        include proxy_params;
      #        proxy_pass http://unix:/run/gunicorn.sock;
      # }

      location / {
              # 显式指定透传Authorization头
              proxy_set_header Authorization $http_authorization;
              # 允许透传非公开定义的头字段
              proxy_pass_header Authorization;
              include proxy_params;
              proxy_pass http://unix:/run/gunicorn.sock;
      }
}

方法2:必须全局保留auth_basic的情况

如果整个站点都需要开启Basic认证,需要额外配置先保存原始的Authorization头再透传给上游:

server {
      listen 80;
      server_name dev.website.com;

      # 预先保存客户端发来的原始Authorization头
      set $auth_header $http_authorization;

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

      location /static {
             alias /home/ubuntu/platform/backend/static;
      }

      auth_basic "Admin Login";
      auth_basic_user_file /etc/nginx/.htpasswd;

      location / {
              # 透传之前保存的原始Authorization头
              proxy_set_header Authorization $auth_header;
              include proxy_params;
              proxy_pass http://unix:/run/gunicorn.sock;
      }
}

额外检查项

确认你客户端发的请求头拼写正确,你给出的示例里AUthorization拼写多了一个大写U,正确拼写是Authorization,请求头拼写错误也会直接导致后端读取不到令牌。

内容的提问来源于stack exchange,提问作者Felix Maximilian Hoffer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:24:06