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;
	}
}
相关推荐
java_logo9 小时前
MILVUS Docker 容器化部署指南
运维·人工智能·docker·容器·prometheus·milvus
渡我白衣9 小时前
计算机组成原理(1):计算机发展历程
java·运维·开发语言·网络·c++·笔记·硬件架构
_OP_CHEN10 小时前
【Git原理与使用】(一)告别文件混乱!Git 初识:从版本灾难到高效管理的终极方案
linux·运维·git·github·运维开发·版本控制·企业级组件
装不满的克莱因瓶10 小时前
【Java架构 搭建环境篇三】Linux安装Git详细教程
java·linux·运维·服务器·git·架构·centos
MC皮蛋侠客10 小时前
Linux安装go及环境配置教程
linux·运维·golang
满天点点星辰10 小时前
Linux命令大全-find命令
linux·运维·服务器
H_z_q240110 小时前
RHCE的条件测试
linux·运维·服务器
wanhengidc10 小时前
免费云手机的安全性如何?
运维·服务器·安全·智能手机·生活
吕了了11 小时前
41 制作自己的wim包+DIY微软官方ISO文件!
运维·windows·microsoft·电脑·系统
谷粒.11 小时前
自动化测试覆盖率从30%到80%的演进历程:策略、挑战与未来展望
运维·网络·深度学习·架构·自动化·transformer·测试覆盖率