PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 2, 2022

[FIXED] How can I set Host as $upstream_addr in Nginx

 September 02, 2022     nginx, nginx-location, nginx-reverse-proxy     No comments   

Issue

I have the following config below on 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>

I tried setting the Host to $upstream_addr, but unfortunately, I'm receiving null in the request. Could anyone please help me in setting up the Host as $upstream_addr. Thanks, Bhaskar.


Solution

As Larry mentioned, the request headers (and body) are fixed before the upstream is selected. Hence your $upstream_addr would always return null.

What you can do is add two levels of proxy. But this might get messy if you have a lot of upstreams of 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;
}
}


Answered By - Aakash Agarwal
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing