使用nginx 1.0将动态proxy_pass传递到$ var [英] Dynamic proxy_pass to $var with nginx 1.0
问题描述
我正在尝试根据环境变量将请求代理到不同的目标.我的方法是将目标url放入自定义变量$ target中,并将其提供给proxy_pass.
I am trying to proxy a request to different targets depending on an environment variable. My approach was to put the target url into the custom variable $target and give this to proxy_pass.
但是将变量与proxy_pass一起使用似乎无效.这个简单的配置会导致nginx发出"502 Bad Gateway"响应.
But using a variable with proxy_pass doesn't seem to work. This simple config leads to a "502 Bad Gateway" response from nginx.
server {
listen 8080;
server_name myhost.example.com;
access_log /var/log/nginx/myhost.access.log;
location /proxy {
set $target http://proxytarget.example.com;
proxy_pass $target;
}
}
没有变量的相同配置有效:
The same config without the variable works:
server {
listen 8080;
server_name myhost.example.com;
access_log /var/log/nginx/myhost.access.log;
location /proxy {
proxy_pass http://proxytarget.example.com;
}
}
真的不可能以这种方式使用proxy_pass还是我只是做错了什么?
Is it really not possible to use proxy_pass this way or am I just doing something wrong?
推荐答案
我最近偶然发现了这种需求,发现为了在proxy_pass目标中使用变量,您需要将解析器设置为error.log.很有可能包含类似no resolver defined to resolve ...
I've recently stumbled upon this need myself and have found that in order to use variables in a proxy_pass destination you need to set a resolver as your error.log would most probably contain something like no resolver defined to resolve ...
在我的情况下,解决方案是使用本地DNS进行以下设置以进行DNS解析:
The solution in my case was to setup the following using a local DNS for DNS resolution:
location ~ /proxy/(.*) {
resolver 127.0.0.1 [::1];
proxy_pass http://$1;
}
在您的情况下,这应该可行:
In your case this should work:
location /proxy {
resolver 127.0.0.1 [::1];
set $target http://proxytarget.example.com;
proxy_pass $target;
}
为使解析器127.0.0.1正常工作,您需要在本地安装bind9. 对于Debian/Ubuntu:
For resolver 127.0.0.1 to work, you need to install bind9 locally. For Debian/Ubuntu:
sudo apt-get install bind9
sudo apt-get install bind9
有关nginx和动态proxy_pass
的更多信息,请参见: http://www.nginx-discovery.com/2011/05/day-51-proxypass-and-resolver.html
More information on nginx and dynamic proxy_pass
ing here: http://www.nginx-discovery.com/2011/05/day-51-proxypass-and-resolver.html
为安全起见,将以前的公共DNS替换为本地DNS 问题.
Replaced the previous public DNS with a local one for security issues.
这篇关于使用nginx 1.0将动态proxy_pass传递到$ var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!