nginx variables (cname) in proxy_pass

六月ゝ 毕业季﹏ 提交于 2021-01-28 05:06:17

问题


i am trying dynamically set a the proxy_pass destination where the variable would be the cname of the original request.

what i have right now is:

server {
    listen       8888;
    server_name (.*).domain.com;

    location / {
        proxy_pass       http://$1.otherdomain.com;
        proxy_set_header Host $1.otherdomain.com;

but unfortunately this ends up in a 502 bad gateway. nothing really works when using a variable in proxy_pass and proxy_set_header.

i also tried to use (?<cname>.+) or (?P<cname>.+) in the server name and $cname as the variable.

what is wrong and why does it end up in a 502?


回答1:


To use regex in server name, you need to prepend the name with a tilde "~"

server_name ~(.*).domain.com;

[UPDATE] Tried it and it successfully set the value in $1. But still get 502 and my nginx error log shows

no resolver defined to resolve xyz.otherdomain.com

even though I point that name to my localhost in my /etc/hosts file.

Find this article that explains this issue well. Basically in this special case (variable in upstream domain name), you need to use the "resolver" directive to point to a dns server (e.g., 8.8.8.8 from google dns server) that can resolve this dynamic domain name.

resolver 8.8.8.8;

It works in my test with a public upstream domain name. If you upstream domain names are local, you need to set up a local dns server for them.




回答2:


The server name for proxy_pass using variables, will be a special situation.

proxy_pass       http://$1.otherdomain.com;

In this case, the server name is searched among the described server groups, and, if not found, is determined using a resolver.

If you do not like to use resolver. You can use below like hosts file.

upstream www1.otherdomain.com { server 10.x.x.1; } 
upstream www2.otherdomain.com { server 10.x.x.2; }


来源:https://stackoverflow.com/questions/15556023/nginx-variables-cname-in-proxy-pass

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