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 ,根据最终访问哪个域名自动设置;
结帖,
没有找到好的方法,为了先让服务能用起来简单的配置了一下;
upstream test_backend { server test1.com max_fails=3; server test2.com backup; } location / { proxy_set_header Host test1.com; proxy_pass http://test_backend ; }
1 phpfpm 2019-05-28 11:48:11 +08:00 test1 自己都不知道自己是啥??? |
2 mooncakejs 2019-05-28 11:49:53 +08:00 via iPhone 分开写, |
3 ytlm OP |
4 ytlm OP |
![]() | 5 KasuganoSoras 2019-05-28 12:22:38 +08:00 proxy_set_header Host $upstream_addr; |
![]() | 6 Citrus 2019-05-28 12:23:00 +08:00 |
![]() | 7 Citrus 2019-05-28 12:24:09 +08:00 @KasuganoSoras upstream_addr 变量在这个要求里面不太试用吧,我记得这个变量会变成实际解析出来的 IP 端口,而不是域名哦。。。 |
![]() | 8 KasuganoSoras 2019-05-28 12:31:56 +08:00 |
![]() | 9 KasuganoSoras 2019-05-28 12:33:11 +08:00 如果 upstream 的域名有多个 IP (例如 CNAME 负载均衡),可以通过修改 Hosts 将它们指向一个固定的 IP |
10 ytlm OP |
11 ytlm OP @Citrus #6 具体后端服务是什么情况不太清楚,有可能是用两个域名做主备,服务是两个,但是连的数据库是一个; 两个域名对应的 ip 都是不一样的; url 都是一样的,所以用 location 区分不出来; |
![]() | 12 est 2019-05-28 14:13:09 +08:00 不加 proxy_set_header 试试呢? |
13 ytlm OP @est #12 不加 proxy_set_header 的话,代理出去的请求头 Host 会被默认设置成 test_backend ; 这个 upstream 的名称 |
![]() | 14 werty 2019-05-28 14:22:35 +08:00 用 openresty 的话, 可以用 rewrite_by_lua 搞一段 lua 脚本, 可以 if else |
![]() | 15 est 2019-05-28 14:26:56 +08:00 |
16 ytlm OP @werty #14 用 rewrite_by_lua 应该不太好做,用 balance_by_lua 应该是可以的; 主要是不想写那么麻烦,想通过简单的配置解决; |
20 mooncakejs 2019-05-28 19:29:56 +08:00 @ytlm 就是二层反代 |
21 liwb2 2019-07-10 21:02:02 +08:00 可以尝试使用 http_map_module 中的 map 指令看看 map http://nginx.org/en/docs/http/ngx_http_map_module.html $upstream_addr http://nginx.org/en/docs/http/ngx_http_upstream_module.html#variables map $upstream_addr $remote_server_name { default test1.com; 'test1.com:port' test1.com; 'test2.com:port' test2.com; } proxy_set_header Host $remote_server_name; 注意 default 取值 |