更改 nginx 反向代理中的主机标头 [英] Change Host header in nginx reverse proxy

查看:79
本文介绍了更改 nginx 反向代理中的主机标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行 nginx 作为站点 example.com 的反向代理,以对在后端服务器中运行的 ruby​​ 应用程序进行负载平衡.我在 nginx 中有以下 proxy_set_header 字段,它会将主机标头传递给后端 ruby​​.这是 ruby​​ 应用程序识别子域名所必需的.

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

现在我想创建一个别名 beta.example.com,但是传递给后端的主机头应该仍然是 www.example.com 否则 ruby​​ 应用程序将拒绝请求.所以我想要类似于下面的内部位置指令.

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

最好的方法是什么?

推荐答案

你不能在 if 块中使用 proxy_pass,所以我建议在设置代理头之前做这样的事情:

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

现在你可以只使用 proxy_passproxy_set_header 而没有 if 块:

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

这篇关于更改 nginx 反向代理中的主机标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆