proxy_set_header
是 Nginx 配置中用于修改或添加传递给后端代理服务器(如 Tomcat、Node.js 等)的 HTTP 请求头的指令。它常用于反向代理场景,确保后端服务能获取正确的客户端信息或自定义数据。
基本语法
location / {
proxy_pass http://backend_server;
proxy_set_header Header-Name "Header-Value";
}
常见用途示例
1. 传递真实客户端 IP
默认情况下,后端服务看到的客户端 IP 会是 Nginx 的 IP。通过以下配置传递真实 IP:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
X-Real-IP
: 客户端的真实 IP。X-Forwarded-For
: 包含所有经过的代理服务器的 IP 链。
2. 修改 Host 头
某些后端服务需要原始的 Host
头(如虚拟主机):
proxy_set_header Host $host;
3. 自定义头
添加自定义头(如认证信息):
proxy_set_header API-Secret "your-secret-key";
4. 关闭不必要的头
隐藏 Nginx 版本等信息:
proxy_set_header Server "";
注意事项
覆盖默认头
Nginx 默认会传递Host
、Connection
等头,使用proxy_set_header
会覆盖这些值。变量支持
可以嵌入 Nginx 变量(如$remote_addr
、$host
),动态生成头内容。多值处理
重复使用同一指令会叠加头部值(需后端支持解析)。生效位置
通常在location
或server
块中配置。
完整示例
”`nginx server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme; # 传递协议(http/https)
proxy_set_header X<br/><br/><br/><font size=1 color=#CCCCCC>内容由零声教学AI助手提供,问题来源于学员提问</font>