Nginx – How to specify search domain name of nginx resolver for proxy_pass

domain-namenginxPROXYresolve

Assuming my server is www.mydomain.com, on Nginx 1.0.6

I'm trying to proxy all request to http://www.mydomain.com/fetch to other hosts, the destination URL is specified as a GET parameter named "url".

For instance, when user requests either one:

http://www.mydomain.com/fetch?url=http://another-server.mydomain.com/foo/bar

http://www.mydomain.com/fetch?url=http://another-server/foo/bar

it should be proxyed to

http://another-server.mydomain.com/foo/bar

I'm using the following nginx config and it works fine only if the url paramter contains domain name, like http://another-server.mydomain.com/; but fails on http://another-server/ on error:

another-server could not be resolved (3: Host not found)

nginx.conf is:

http {
...
# the DNS server
resolver 171.10.129.16;
server {
    listen       80;
    server_name  localhost;
    root /path/to/site/root;

    location = /fetch {            
        proxy_pass $arg_url;
    }
}

Here, I'd like to resolve all URL without domain name as host name in mydomain.com, in /etc/resolv.conf, it's possible to specify default search domain name for the whole Linux system, but it doesn't affect nginx resolver:

search mydomain.com

Is it possible in Nginx? Or alternatively, how to "rewrite" the url parameter so that I can add the domain name?

Best Answer

nginx performs its own DNS resolution and doesn't use the libc library, which is why /etc/resolv.conf doesn't have an effect. I can't find any option to specify a search domain, so rewriting the URL is your only option. Something like this should do the trick:

location /fetch {
    # Don't rewrite if we've already rewritten or the request already contains the full domain
    if ($arg_url !~ mydomain.com) {
        rewrite ^/fetch?url=http://([^/]+)(/?.*)$ /fetch?url=http://$1.mydomain.com$2;
    }
    proxy_pass $arg_url;
}
Related Topic