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;
	}
}
相关推荐
DolphinScheduler社区17 小时前
DolphinScheduler 3.1.3 跨越升级 3.4.1:基于 API 的自动化迁移方案
大数据·运维·自动化·任务调度·海豚调度
happymade17 小时前
全网拓扑自动发现与服务器全维度监控的技术实践
linux·运维·服务器·网络·zabbix·路由器·prometheus
Ysn071917 小时前
中文乱码:在 Docker 容器中设置中文语言环境
运维·python·docker·容器
OpsEye18 小时前
数据库连接池爆了,这3个命令能救你一次
运维·数据库·后端
辣椒思密达18 小时前
住宅IP纯净度评估方法:黑名单、风险评分与历史行为检测
运维·服务器·网络
寻道模式18 小时前
【运维心得】2000块的打印机复活记
运维·hp·喷墨打印机·墨盒
zxd02031118 小时前
EFK(Elasticsearch + Fluentd + Kibana) 日志收集系统
运维·docker·jenkins
ccice0119 小时前
硬核实战:调用Gemini多模态管道,直击办公中的图表解析、发票识别与自动化脚本生成(国内镜像免费方案)
运维·自动化
爱喝水的鱼丶19 小时前
SAP-ABAP:数据类型与数据对象(8篇) 第七篇:进阶优化篇——基于类型与对象特征的性能优化技巧
运维·数据库·学习·性能优化·sap·abap·开发交流
DFT计算杂谈19 小时前
VASP新手入门: IVDW 色散修正参数
linux·运维·服务器·python·算法