nginx 反向代理设置头` Host $host;`,请问为何需要这一步呢?

Nginx在配置反向代理的时候:

location / {
    proxy_pass https://demo.com; 
    proxy_set_header Host $host; 
}

我们看到有设置头 Host $host;,请问为何需要这一步呢?

阅读 5.7k
2 个回答

https://docs.nginx.com/nginx/...

By default, NGINX redefines two header fields in proxied requests, “Host” and “Connection”, and eliminates the header fields whose values are empty strings. “Host” is set to the $proxy_host variable, and “Connection” is set to close.

To change these setting, as well as modify other header fields, use the proxy_set_header directive. This directive can be specified in a location or higher. It can also be specified in a particular server context or in the http block. For example:

nginx默认会修改Host和Connection值,需要用proxy_set_header改回去。以及为空的header会被消除。
其他header信息会原样传递。

host 的作用

可能会存在这种情况:

  1. 一个服务器上面有一个 ip。
  2. 这台服务器上面存在多个域名绑定的站点。
  3. 多个域名都指向这个 ip。

带上 Host 的作用就是,让你在相同 ip 多站点的情况下,能够区分你要访问这台服务器的哪个站点的资源。

示例

反向代理要加上,就是要让这部分信息不丢失。

不设置的话,nginx 不会主动将你的头信息传递。

更新

经过测试,nginx 会修改 Host
上面是不加上 proxy_set_header Host $host; 的结果,Host 会变为代理的目的地址。
下面是加上的结果。
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题