nginx需显式配置proxy_set_header authorization $http_authorization;才能透传authorization头,推荐用map过滤空值,并支持从cookie或url参数提取token,同时注意 underscores_in_headers、后端兼容性及websocket配置。

要让后端服务能收到客户端发来的 Authorization 头,必须显式配置 proxy_set_header Authorization $http_authorization;。Nginx 默认不透传这个头,不是漏了,是设计如此。
基础写法:原样透传
在 location 或 server 块里加上这行即可:
proxy_set_header Authorization $http_authorization;
注意变量名必须是 $http_authorization(全小写、带下划线),写成 $http_Authorization 或 $http_authorisation 都会失效。
避免空头导致鉴权失败
如果客户端没带 Authorization,$http_authorization 是空字符串,那上面那行配置会让后端收到一个空的 Authorization: 头——有些框架会直接拒绝。更稳妥的做法是用 map 过滤:
- 在
http块里定义:map $http_authorization $pass_auth {<br> "" ""; # 空值不传<br> default $http_authorization;<br>} - 再在
location里写:proxy_set_header Authorization $pass_auth;
从其他位置提取 Token
当 Token 不在 Authorization 头里,而在 Cookie 或 URL 参数中时:
- 从 Cookie 提取(如
Cookie: token=abc123):proxy_set_header Authorization "Bearer $cookie_token"; - 从 URL 参数提取(如
?token=abc123):proxy_set_header Authorization "Bearer $arg_token"; - 组合使用更可靠:用
map判断优先级,比如先查$http_authorization,再 fallback 到$cookie_token
配套注意事项
光传 Authorization 不够,还得兼顾几个关键点:
- 确保没被其他配置覆盖,检查有没有类似
proxy_set_header Authorization "";的清空语句 - 如果用了自定义头(如
X-Auth-Token),需加underscores_in_headers on;,否则 Nginx 会忽略它 - 后端是否真认这个头?Spring Security 默认只看
Authorization,不认X-Auth-Token - WebSocket 场景下,同样适用
$http_authorization,但必须配齐proxy_http_version 1.1和Upgrade/Connection头











