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

时间:2018-04-04 13:20:53

标签: nginx nginx-location nginx-reverse-proxy

我在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,但不幸的是,我在请求中收到空。 任何人都可以帮我设置主机为$ upstream_addr。 谢谢, 巴斯卡尔。

1 个答案:

答案 0 :(得分:0)

正如Larry所提到的,请求标题(和正文)在选择上游之前是固定的。因此,$ upstream_addr将始终返回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;
}
}