Nginx Access Log: log the real user’s IP instead of the proxy

Profile image of Mattias Geniar

Mattias Geniar, December 11, 2011

Follow me on Twitter as @mattiasgeniar

If you’re running Nginx behind a proxy or a caching engine like Varnish or Squid, you’ll see your access logs get filled with lines that mention your Proxy or Caching engine’s IP instead of the real user’s IP address.

To change that, add the following line in your general nginx.conf in the http {} section.

log_format main '$http_x_forwarded_for - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent "$http_referer" '
'"$http_user_agent"' ;

The change there is that the standard $remote_addr is replaced by $http_x_forwarded_for that your proxy/cache will pass along.

Somewhere along your config you’ll have a line similar to this:

access_log      /var/www/site/logs/access.log main;

Add the main parameter at the end, to tell Nginx you’re using that custom log format you created above.

Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.