Change Host header in nginx reverse proxy

You cannot use proxy_pass in if block, so I suggest to do something like this before setting proxy header:

set $my_host $http_host;
if ($http_host = "beta.example.com") {
  set $my_host "www.example.com";
}

And now you can just use proxy_pass and proxy_set_header without if block:

location / {
  proxy_pass http://rubyapp.com;
  proxy_set_header Host $my_host;
}

I was trying to solve the same situation, but with uwsgi_pass.

After some research, I figured out that, in this scenario, it's required to:

uwsgi_param HTTP_HOST $my_host;

Hope it helps someone else.


Just a small tip. Sometimes you may need to use X-Forwarded-Host instead of Host header. That was my case where Host header worked but only for standard HTTP port 80. If the app was exposed on non-standard port, then this port was lost when the app generated redirects. So finally what worked for me was:

proxy_set_header X-Forwarded-Host $http_host;

map is better than set + if.

map $http_host $served_host {
    default $http_host;
    beta.example.com www.example.com;
}

server {
    [...]

    location / {
        proxy_pass http://rubyapp.com;
        proxy_set_header Host $served_host;
    }
}

Tags:

Nginx