Nginx 的 proxy_set_header 不自动传递原始请求头,需显式设置;自定义头如 X-Real-IP 可用 $http_x_real_ip 透传,但 Host、Connection 等 hop-by-hop 头被自动过滤,Authorization 需显式配置才能转发。

在 Nginx 中,proxy_set_header 本身**不会自动传递原始请求头**,它默认只设置固定的值(比如 Host $host)。若想把客户端发来的原始请求头原样透传给后端,需**显式声明**,且注意部分头字段会被 Nginx 自动过滤或重写。
哪些原始请求头能直接透传?
大多数自定义头(如 X-Real-IP、X-Forwarded-For、X-Request-ID)可直接用变量引用:
-
proxy_set_header X-Real-IP $remote_addr;—— 客户端真实 IP(非代理 IP) -
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;—— 推荐用$proxy_add_x_forwarded_for,它会在原有值后追加$remote_addr,避免覆盖 -
proxy_set_header X-Forwarded-Proto $scheme;—— 透传 HTTP/HTTPS 协议 -
proxy_set_header X-Forwarded-Host $host;—— 透传原始 Host -
proxy_set_header X-Original-Method $request_method;—— 方法名(GET/POST 等)
如何透传任意原始请求头(包括自定义头)?
Nginx 不提供“通配符式”转发所有头的指令,但可通过以下方式实现等效效果:
- 对已知的自定义头,逐条写:
proxy_set_header X-User-Token $http_x_user_token;
(注意:原始头名转为小写、中划线变下划线,并加$http_前缀) -
$http_变量仅在请求头存在时有值;若客户端没发该头,对应变量为空,Nginx 不会发送该 header 到后端 - 例如客户端带
X-Trace-ID: abc123,Nginx 中用$http_x_trace_id引用
哪些头不能直接透传?为什么?
以下头字段被 Nginx 默认忽略或强制改写,无法通过 $http_* 直接获取原始值:
FastAPI + Flask 混合部署最佳实践,解决路由定义、API 代理等常见问题,适用于同时运行 FastAPI API 与 Flask 前端的场景。
-
Host:Nginx 默认用
$host或$http_host,但若客户端 Host 头非法或缺失,Nginx 可能用 server_name 替代。建议用proxy_set_header Host $http_host;尽量保留,同时确保underscores_in_headers on;(若 Host 含下划线) - Connection / Keep-Alive / Proxy-Authenticate / Proxy-Authorization / TE / Trailer / Transfer-Encoding / Upgrade:这些属于“hop-by-hop”头,Nginx 会主动删除,不转发给后端(符合 HTTP/1.1 规范)
-
Authorization:默认会被清除(出于安全考虑),如需透传,必须显式设置:
proxy_set_header Authorization $http_authorization;
实用配置示例
一个较完整的反向代理头透传片段:
underscores_in_headers on;
<p>location / {
proxy_pass <a href="https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e">https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e</a>;</p><pre class="brush:php;toolbar:false;">proxy_set_header Host $http_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;
# 透传常见自定义头
proxy_set_header X-Request-ID $http_x_request_id;
proxy_set_header X-User-ID $http_x_user_id;
proxy_set_header Authorization $http_authorization;
# 若前端可能发 X-Forwarded-Host,也一并透传
proxy_set_header X-Forwarded-Host $http_x_forwarded_host;}










