Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic proxy_pass to $var with nginx 1.0

Tags:

nginx

proxy

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.

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

Is it really not possible to use proxy_pass this way or am I just doing something wrong?

like image 927
Sebastian Heuer Avatar asked Apr 21 '11 11:04

Sebastian Heuer


1 Answers

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 ...

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

For resolver 127.0.0.1 to work, you need to install bind9 locally. For Debian/Ubuntu:

sudo apt-get install bind9

More information on nginx and dynamic proxy_passing here: http://www.nginx-discovery.com/2011/05/day-51-proxypass-and-resolver.html

Edit: Replaced the previous public DNS with a local one for security issues.

like image 99
soulseekah Avatar answered Oct 02 '22 00:10

soulseekah