proxy_set_header设置Host为$proxy_host,$host与$local_host的区别

https://blog.csdn.net/a19860903/article/details/49914131

先来看下proxy_set_header的语法

语法:proxy_set_header field value;
默认值:
proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
上下文:httpserverlocation

允许重新定义或者添加发往后端服务器的请求头。value可以包含文本、变量或者它们的组合。 当且仅当当前配置级别中没有定义proxy_set_header指令时,会从上面的级别继承配置。 默认情况下,只有两个请求头会被重新定义:

proxy_set_header Host       $proxy_host;
proxy_set_header Connection close;

nginx对于upstream默认使用的是基于IP的转发,因此对于以下配置:

 

Xml代码  收藏代码

  1. upstream backend {  
  2.     server 127.0.0.1:8080;  
  3. }  
  4. upstream crmtest {  
  5.     server crmtest.aty.sohuno.com;  
  6. }  
  7. server {  
  8.         listen       80;  
  9.         server_name  chuan.aty.sohuno.com;  
  10.         proxy_set_header Host $http_host;  
  11.         proxy_set_header x-forwarded-for  $remote_addr;  
  12.         proxy_buffer_size         64k;  
  13.         proxy_buffers             32 64k;  
  14.         charset utf-8;  
  15.   
  16.         access_log  logs/host.access.log  main;  
  17.         location = /50x.html {  
  18.             root   html;  
  19.         }  
  20.     location / {  
  21.         proxy_pass backend ;  
  22.     }  
  23.           
  24.     location = /customer/straightcustomer/download {  
  25.         proxy_pass http://crmtest;  
  26.         proxy_set_header Host $proxy_host;  
  27.     }  
  28. }  

 

当匹配到/customer/straightcustomer/download时,使用crmtest处理,到upstream就匹配到crmtest.aty.sohuno.com,这里直接转换成IP进行转发了。假如crmtest.aty.sohuno.com是在另一台nginx下配置的,ip为10.22.10.116,则$proxy_host则对应为10.22.10.116。此时相当于设置了Host为10.22.10.116。如果想让Host是crmtest.aty.sohuno.com,则进行如下设置:

 

proxy_set_header Host crmtest.aty.sohuno.com;

如果不想改变请求头“Host”的值,可以这样来设置:

proxy_set_header Host       $http_host;

但是,如果客户端请求头中没有携带这个头部,那么传递到后端服务器的请求也不含这个头部。 这种情况下,更好的方式是使用$host变量——它的值在请求包含“Host”请求头时为“Host”字段的值,在请求未携带“Host”请求头时为虚拟主机的主域名:

proxy_set_header Host       $host;

此外,服务器名可以和后端服务器的端口一起传送:

proxy_set_header Host       $host:$proxy_port;

如果某个请求头的值为空,那么这个请求头将不会传送给后端服务器:

proxy_set_header Accept-Encoding "";

 

  • 点赞 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_world!

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值