标签:nginx proxy_set_header host参数
proxy_set_header HOST $host这个参数的赋值,在做转发的时候非常重要,他直接可以决定server_name匹配值,下面我们看一个例子:
先说一下测试架构:
nginx1(10.0.0.8) -> nginx2(10.0.0.1) -> tomcat(10.0.0.100)
一、各节点配置信息
1、还需要一台测试机,测试机上需要首先配置host:
$ cat /etc/hosts
10.0.0.8 sso.cbpmgt.com
2、tomcat上面只有一个测试页面,内容是Hello World
3、以下是nginx1的配置,注释host参数的配置:
upstream sso {
server 10.0.0.1:80 max_fails=2 fail_timeout=30s;
}
server {
listen 80;
server_name sso.cbpmgt.com ;
location / {
access_log /export/log/nginx/sso_access.log main;
error_log /export/log/nginx/sso_error.log warn;
proxy_pass http://sso/;
proxy_redirect off;
#proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
4、以下是nginx2的配置:
upstream sso-yz {
server 10.0.0.100:80 max_fails=2 fail_timeout=30s;
}
server {
listen 80;
server_name sso;
location / {
access_log /export/log/nginx/sso_m6-yz.log main;
error_log /export/log/nginx/sso_m6-yz-error.log warn;
proxy_pass http://sso-yz/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
二、测试
1、测试host参数不配置的情况:
现在从测试机发起测试,在测试机器上执行:curl http://sso.cbpmgt.com/test.htm ,可以看到正常访问到tomcat:
# curl http://sso.cbpmgt.com/test.htm
Hello World
2、测试host参数配置的情况:
现在我们改下nginx1的配置,配置更改如下,将host参数配置上:
upstream sso {
server 10.0.0.1:80 max_fails=2 fail_timeout=30s;
}
server {
listen 80;
server_name sso.cbpmgt.com ;
location / {
access_log /export/log/nginx/sso_access.log main;
error_log /export/log/nginx/sso_error.log warn;
proxy_pass http://sso/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
3、还是从测试机发起测试:curl http://sso.cbpmgt.com/test.htm,这里不会有任何结果,如下:
# curl http://sso.cbpmgt.com/test.htm
#
原因:因为在nginx2上接收到的host是sso.cbpmgt.com,这将匹配不到sso这个server_name,导致访问失败
总结一下:proxy_set_header Host $host;这条命令会将请求的host(这里是sso.cbpmgt.com)传递给后端的服务,nginx也是根绝这个host去和server_nanme做匹配,然后相应的往后代理。在第一种情况的时候,因为注释掉了http头host的参数赋值,所以在nginx2拿到的是sso这个host值。
标签:nginx proxy_set_header host参数
原文地址:http://tsing.blog.51cto.com/3761021/1677705