如何在 Nginx 中将 Host 设置为 $upstream_addr

How can I set Host as $upstream_addr in Nginx

我在 Nginx.conf

上有以下配置
<b>
http {
    log_format my_upstream '$remote_addr [$time_local] "$request" $status'
        '"$upstream_addr" $upstream_response_time $upstream_http_etag $host $http_host';
    access_log /var/log/nginx/upstream.log my_upstream;

upstream myapp{
         ip_hash;
         server x.x.x.174:8001;
         server x.x.x.96:8001;
     }

    server {
     listen 9000;
     #websocket
     location /jms {
         proxy_pass http://myapp/jms;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection "Upgrade";
         proxy_set_header Host $upstream_addr;
     }

     location / {
        proxy_pass http://myapp;
     }
     }
}
</b>

我尝试将主机设置为 $upstream_addr,但不幸的是,我在请求中收到 null。 谁能帮我将主机设置为 $upstream_addr。 谢谢, 巴斯卡.

正如 Larry 提到的,请求 headers(和 body)在选择上游之前是固定的。因此你的 $upstream_addr 总是 return null.

您可以做的是添加两级代理。但是如果你有很多 myapp 的上游,这可能会变得混乱。

upstream myapp{
     ip_hash;
     server x.x.x.174:8001;
     server x.x.x.96:8001;
 }

upstream main {
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
}
server {
  listen      8001 ;

  location / {
    proxy_pass       http://x.x.x.174:8001/jms;
    proxy_set_header Host x.x.x.174:8001;
  }
}

server {
  listen      8002 ;
  location / {
     proxy_pass       http://x.x.x.96:8001/jms;
     proxy_set_header Host x.x.x.96:8001;
  }
}

server {
listen 9000;
#websocket
location /jms {
     proxy_pass http://main;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
}

location / {
    proxy_pass http://myapp;
}
}