Nginx 原生配置中没有名为 pass_host 的指令,实现保留原始 Host 头信息需要在 location 块中使用 proxy_set_header Host $http_host;。该设置适用于反向代理场景,确保后端服务能获取客户端请求的真实域名,风险边界在于配置错误可能导致后端无法识别请求或重定向循环。
先说结论:Nginx 通过 proxy_set_header 指令实现 Host 头传递,而非 pass_host 参数。
- 适合:Nginx 反向代理需要后端识别原始域名的场景
- 先准备:备份 nginx.conf 或站点配置文件
- 验收:通过 curl 命令或后端日志确认 Host 头值
命令速用版
直接修改 Nginx 配置文件,在 server 或 location 块中添加 proxy_set_header 指令。
location / {
proxy_pass http://backend_server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}为什么会这样
HTTP 协议中 Host 头用于标识请求的目标主机,反向代理默认可能修改该值。Nginx 作为反向代理时,默认会将 Host 头设置为 proxy_pass 指定的上游地址,导致后端无法获取客户端原始域名。
分步处理
1. 找到配置文件,通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/conf.d/ 目录下。
2. 在对应的 server 块中找到 location 配置。
3. 添加或修改 proxy_set_header Host 指令。
4. 执行 nginx -t 检查配置语法。
5. 执行 nginx -s reload 重载配置。
怎么验证是否生效
使用 curl 命令模拟请求并查看 verbose 输出,或检查后端应用日志。
curl -v -H "Host: example.com" http://nginx_ip/观察后端接收到的 Host 头是否为 example.com。
常见坑
1. $host 与 $http_host 区别:$host 不包含端口,$http_host 包含端口,根据后端需求选择。
2. 端口丢失:如果后端需要非标准端口,需确保 Host 头中携带端口信息。
3. 配置优先级:location 块中的配置会覆盖 server 块中的配置。
常见问题
pass_host 是 Nginx 原生指令吗
不是,Nginx 原生没有 pass_host 指令,这是部分面板的抽象说法。
为什么要保留原始 Host 头
后端服务需要根据 Host 头生成链接、处理重定向或进行多租户识别。
配置后需要重启 Nginx 吗
不需要重启,执行 reload 重载配置即可生效。
参考来源
Nginx Official Documentation, ngx_http_proxy_module, proxy_set_header. URL: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header