Using NginX behind a load balancer with correct ip addresses in the logs

If you have Varnish + NginX on the server, every visitor in the NginX logs will show up with the same ip address - 127.0.0.1. There are two options:

  1. Change the log format
  2. Make NginX pick up the correct ip address directly

First you need to make Varnish send this ip address to the backend. Add the following lines to the vcl_recv section:

if (req.restarts == 0) {
  if (req.http.x-forwarded-for) {
    set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }
}

Actually you can get away with just:

set req.http.X-Forwarded-For = client.ip;

Now make sure realip is enabled in your NginX:

nginx -V 2>&1 |grep realip

If everything’s OK, add these lines to the NginX config file (/etc/nginx/nginx.conf) in the http section:

set_real_ip_from   127.0.0.1;
real_ip_header      X-Forwarded-For;

Check the config:

nginx -t

Restart Varnish and NginX:

/etc/init.d/varnish restart && /etc/init.d/nginx restart

Read the logs.

Categories:

Updated: