Get client public ip address with nginx

Random typography letters
Because of some automated cronjob, I need a script to get the public IP address associated to the host's Internet connection. There are a ton of websites that show you your public IP address, but it's not always easy to parse HTML with a simple shell script, and I do prefer self-hosted solutions.

Now, there are a lot of ways to do it, and I went for something simple, requiring just Nginx. No CGI, no PHP or some high-level language.

So here it is :

location /ip {
  default_type text/plain;
  return 200 "$remote_addr\n";
  }

This does just what it's made to do, plain and simple. So simple I'm not sure what to add. Maybe one thing : you can add some more locations with some other variables if you need them, such as $http_user_agent for the user agent. More variables can be found in the Nginx documentation.

I hope you enjoyed this post ! If you did, please share it on your favorite social networks :-)

Photo by Amador Loureiro on Unsplash.