Nginx 多层嵌套 proxy_set_header 的正确方法

为什么不能直接嵌套

在编辑 nginx.conf 时,我们常有一种场景,即需要给所有服务一个通用的 proxy_set_header 集合,对于一些需要特殊处理的服务,定制一些独特的 proxy_set_header。

此时,你可能会这么写:

复制代码
http {
	##
	# Virtual Host Configs
	##
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_set_header X-Forwarded-Proto $scheme;
	proxy_set_header X-Forwarded-Host $host;
	proxy_set_header X-Forwarded-Port $server_port;
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header Host $host;

	server {
	    listen       443 ssl;
	    server_name  demo.domain.com;
	
	    ssl_certificate     /etc/nginx/cert_file/fullchain.pem;            
	    ssl_certificate_key /etc/nginx/cert_file/key.pem;
	
	    location / {
		    proxy_pass http://127.0.0.1:11001/;
	        proxy_set_header Host special.domain.com;
	    }
	
	    error_page 497 https://$host:$server_port$request_uri;
	}
}

但运行起来后,你会发现,在外层设置的 proxy_set_header 全部没有生效。原因是 nginx 仅在里层没有配置任何 proxy_set_header 时,才会继承外层的 proxy_set_header 设置。详见 Nginx 官方文档

正确方法

如果你仔细看过 nginx 的 /etc/nginx 目录,便会发现 nginx 给你默认创建了一个文件 proxy_params。

复制代码
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;

在实际使用时,你可以复用并修改这个文件,或者创建一个类似的新文件,并在每个服务中增加一行include /etc/nginx/proxy_params,在需要定制 header 时,在 include 行的上方增加定制的内容,即可实现继承通用 header 的功能。

复制代码
http {
	##
	# Virtual Host Configs
	##

	server {
	    listen       443 ssl;
	    server_name  demo.domain.com;
	
	    ssl_certificate     /etc/nginx/cert_file/fullchain.pem;            
	    ssl_certificate_key /etc/nginx/cert_file/key.pem;
	
	    location / {
		    proxy_pass http://127.0.0.1:11001/;
	        proxy_set_header Host special.domain.com;
	        include /etc/nginx/proxy_params;
	    }
	
	    error_page 497 https://$host:$server_port$request_uri;
	}
}
相关推荐
上天_去_做颗惺星 EVE_BLUE12 分钟前
Docker入门教程:常用命令与基础概念
linux·运维·macos·docker·容器·bash
孙克旭_7 小时前
PXE_Kickstart_无人值守自动化安装系统
linux·运维·自动化
π大星星️9 小时前
HAProxy + Keepalived + Nginx 高可用负载均衡系统
运维·nginx·负载均衡
IT专业服务商9 小时前
联想 SR550 服务器,配置 RAID 5教程!
运维·服务器·windows·microsoft·硬件架构
Johny_Zhao11 小时前
K8S+nginx+MYSQL+TOMCAT高可用架构企业自建网站
linux·网络·mysql·nginx·网络安全·信息安全·tomcat·云计算·shell·yum源·系统运维·itsm
专注代码七年11 小时前
在Windows 境下,将Redis和Nginx注册为服务。
windows·redis·nginx
UpUpUp……12 小时前
Linux--JsonCpp
linux·运维·服务器·c++·笔记·json
xixingzhe213 小时前
Nginx 配置多个监听端口
服务器·前端·nginx
Clockwiseee13 小时前
文件上传总结
运维·服务器·学习·文件上传
liyi_hz200813 小时前
O2OA(翱途)开发平台系统安全-用户登录IP限制
运维·服务器·网络·o2oa开发