Categories
SysOps

How to display remote address using Nginx

A long time ago I have described how to check external IP address using ssh, so today I will display remote address using Nginx web server.

Use the following virtual host configuration to simply return the remote address in the response body.

server {
  server_name _;
  location / {
    default_type text/plain;

    set $response_body                   "X-Real-IP:          $remote_addr\n";

    if ($http_x_forwarded_for) {
      set $response_body "${response_body}X-Forwarded-For:    $http_x_forwarded_for\n";     
    }

    if ($http_x_forwarded_proto) {
      set $response_body "${response_body}X-Forwarded-Proto:  $http_x_forwarded_proto\n";
    }

    if ($http_x_forwarded_host) {
      set $response_body "${response_body}X-Forwarded-Host:   $http_x_forwarded_host\n";
    }

    if ($http_x_forwarded_server) {
      set $response_body "${response_body}X-Forwarded-Server: $http_x_forwarded_server\n";
    }

    return 200 $response_body;
  }
}

Use browser or curl utility to check IP address directly.

X-Real-IP:          172.16.0.111

Use browser or curl utility to check IP address via NAT. Notice that the remote address will point to the NAT machine.

X-Real-IP:          172.16.0.1

Use browser or curl utility to check IP address via proxy.

X-Real-IP:          172.16.0.102
X-Forwarded-For:    172.16.0.1
X-Forwarded-Proto:  http
X-Forwarded-Host:   172.16.0.102:80
X-Forwarded-Server: 172.16.0.102

Sample virtual host configuration that will proxy traffic to the http://172.16.0.101 address.

server {
  server_name _;
  location / {
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_set_header X-Forwarded-Host $host:$server_port;
    proxy_set_header X-Forwarded-Server $host;

    proxy_pass http://172.16.0.101;
  }
}