求教, nginx 怎么在 proxy_pass 的时候 携带 http 请求头部 Host 参数,并且值是 upstream 中配置的 server,不是客户端携带的 Host;

2019-05-28 11:14:38 +08:00
 ytlm
upstream test_backend {
    server test1.com;
    server test2.com;
}

location / {
    proxy_set_header Host $host;
    proxy_pass http://test_backend ;
}

这里的 $host 是请求客户端的 Host,代理过去也是客户端请求过来的 Host,不是我想要的;

如果配置成 $proxy_host,我测试发现代理过去的 Host 设置成 test_backend,也不是我想要的;

求教:
我想要的代理过去的 Host  是 upstream 中配置的 test1.com 或者 test2.com ,根据最终访问哪个域名自动设置;

4474 次点击
所在节点    NGINX
22 条回复
phpfpm
2019-05-28 11:48:11 +08:00
test1 自己都不知道自己是啥???
mooncakejs
2019-05-28 11:49:53 +08:00
分开写,
ytlm
2019-05-28 12:13:56 +08:00
@phpfpm #1 test1.comtest2.com 都是后端的服务,我不知道那边的处理逻辑,但是如果不携带正确的 Host 代理请求就会失败,
ytlm
2019-05-28 12:20:58 +08:00
@mooncakejs #2 这个分开写是指什么呀?

location 是一样的,upstream 分开写的话,感觉不好写
KasuganoSoras
2019-05-28 12:22:38 +08:00
proxy_set_header Host $upstream_addr;
Citrus
2019-05-28 12:23:00 +08:00
这个要求有点诡异啊,如果 test1.comtest2.com 是不同的服务,为啥要在同一个 location 里返回。。。这不是导致每次刷新都会看到不一样的页面么。。。
原版 nginx 似乎做不到这个。
另外不推荐这么些,nginx 会缓存 dns 解析的结果。如果域名指向的 IP 变了,nginx 会在 TTL 之后再更新。
如果真的要这么玩,可以试下 openresty 的 balance_by_lua,用 lua 脚本选择后端 IP,然后修改请求头。
Citrus
2019-05-28 12:24:09 +08:00
@KasuganoSoras upstream_addr 变量在这个要求里面不太试用吧,我记得这个变量会变成实际解析出来的 IP 端口,而不是域名哦。。。
KasuganoSoras
2019-05-28 12:31:56 +08:00
可以试下
if($upstream_addr = "test1.com 的 IP") {
proxy_set_header Host test1.com;
}
if($upstream_addr = "test2.com 的 IP") {
proxy_set_header Host test2.com;
}
... 以此类推 ...
KasuganoSoras
2019-05-28 12:33:11 +08:00
如果 upstream 的域名有多个 IP (例如 CNAME 负载均衡),可以通过修改 Hosts 将它们指向一个固定的 IP
ytlm
2019-05-28 13:54:29 +08:00
@KasuganoSoras #5 这个变量得到的是一个 ip 地址,我想要的是域名;

proxy_set_header 不能用到这个 if 块下面;
ytlm
2019-05-28 14:07:40 +08:00
@Citrus #6 具体后端服务是什么情况不太清楚,有可能是用两个域名做主备,服务是两个,但是连的数据库是一个;

两个域名对应的 ip 都是不一样的;

url 都是一样的,所以用 location 区分不出来;
est
2019-05-28 14:13:09 +08:00
不加 proxy_set_header 试试呢?
ytlm
2019-05-28 14:15:32 +08:00
@est #12 不加 proxy_set_header 的话,代理出去的请求头 Host 会被默认设置成 test_backend ; 这个 upstream 的名称
werty
2019-05-28 14:22:35 +08:00
用 openresty 的话, 可以用 rewrite_by_lua 搞一段 lua 脚本, 可以 if else
est
2019-05-28 14:26:56 +08:00
@ytlm 实在不行,这个办法可以保底。在 nginx 里给 test1.com test2.com 分别建一个反代,proxy_set_header 设置好。

然后再用你这个配置,指向 nginx 自己的反代。

二层反代。
ytlm
2019-05-28 14:32:03 +08:00
@werty #14 用 rewrite_by_lua 应该不太好做,用 balance_by_lua 应该是可以的;
主要是不想写那么麻烦,想通过简单的配置解决;
ytlm
2019-05-28 14:33:45 +08:00
@est #15 没有太明白这个呢,感觉不是好分开的,因为 url 是同一个;
firebroo
2019-05-28 17:08:02 +08:00
@ytlm 他的意思是在 testx.com 和你现有的 nginx 之前再加个 nginx
firebroo
2019-05-28 17:08:21 +08:00
@firebroo 之前=》之间
mooncakejs
2019-05-28 19:29:56 +08:00
@ytlm 就是二层反代

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/568300

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX