Change Host header in nginx reverse proxy

随声附和 提交于 2021-02-17 08:48:51

问题


I am running nginx as reverse proxy for the site example.com to loadbalance a ruby application running in backend server. I have the following proxy_set_header field in nginx which will pass host headers to backend ruby. This is required by ruby app to identify the subdomain names.

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

Now I want to create an alias beta.example.com, but the host header passed to backend should still be www.example.com otherwise the ruby application will reject the requests. So I want something similar to below inside location directive.

if ($http_host = "beta.example.com") {
    proxy_pass http://rubyapp.com;
    proxy_set_header Host www.example.com;
}

What is the best way to do this?


回答1:


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;
}



回答2:


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;
    }
}



回答3:


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.




回答4:


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;


来源:https://stackoverflow.com/questions/14352690/change-host-header-in-nginx-reverse-proxy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!