nginxproxypass

How to use nginx proxy_pass with $remote_addr?


I'm trying to include $remote_addr or $http_remote_addr on my proxy_pass without success. The rewrite rule works:

location ^~ /freegeoip/ {  
  rewrite ^ http://freegeoip.net/json/$remote_addr last;
}

The proxy_pass without the $remote_addr works, but freegeoip does not read the x-Real-IP:

location ^~ /freegeoip/ {
  proxy_pass http://freegeoip.net/json/;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $host;
}

Then, I'm adding the ip to the end of the request:

location ^~ /freegeoip/ {
  proxy_pass http://freegeoip.net/json/$remote_addr;
}

but nginx reports this error:

no resolver defined to resolve freegeoip.net

Solution

  • If the proxy_pass statement has no variables in it, then it will use the gethostbyaddr system call during startup or reload and will cache that value permanently. If there are any variables, such as using either of the following:

    set $originaddr http://origin.example.com;
    proxy_pass $originaddr;
    
    # or:
    proxy_pass http://origin.example.com$request_uri;
    

    then nginx will use a built-in resolver, and the resolver directive must be present. resolver is probably a misnomer; think of it as "which DNS server will the built-in resolver use". Since NGINX 1.1.9, the built-in resolver will honor DNS TTL values. Before then it used a fixed value of 5 minutes.