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;
	}
}
相关推荐
学烹饪的小胡桃19 小时前
WGCAT工单系统 v1.2.7 更新说明
linux·运维·服务器·网络·工单系统
BigBigHang19 小时前
【docker】离线设备安装镜像
运维·docker·容器
学好statistics和DS19 小时前
Docker文件与本地文件,系统
运维·docker·容器
liuc031719 小时前
docker下安装SearXNG
运维·docker·容器
云飞云共享云桌面19 小时前
非标自动化工厂的设计云桌面为什么要选云飞云智能共享云桌面?
大数据·运维·服务器·网络·自动化·负载均衡
翼龙云_cloud19 小时前
阿里云渠道商:阿里云自动扩缩容配置教程
运维·服务器·阿里云·云计算
别多香了20 小时前
系统批量运维管理器 paramiko
linux·运维·服务器
杨云龙UP20 小时前
Linux LVM 在线扩容标准操作流程_20260102
linux·运维·服务器·centos·ux
微凉的衣柜20 小时前
Windows Server 使用 Nginx 反向代理实现域名访问内网 Gradio 应用
运维·windows·nginx
warton8820 小时前
ubuntu24.04 安装mysql8.0.36
linux·运维·mysql