Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dublado/30494c771730437ee88209f168b9affd to your computer and use it in GitHub Desktop.
Save dublado/30494c771730437ee88209f168b9affd to your computer and use it in GitHub Desktop.

How to log real user’s IP address with Nginx in log files

How to log the real user’s IP instead of the proxy server?

You need use the ngx_http_realip_module module. It is used to change the client address and optional port to the one sent in the specified header fields. Edit your nginx.conf or default.conf file:

$ sudo vi /etc/nginx/conf.d/default.conf

And set the following two directives:

    set_real_ip_from  192.168.1.4;
    real_ip_header    X-Forwarded-For;

Save and close the file. Where,

  1. set_real_ip_from 192.168.1.4; Set trusted addresses that are known to send correct replacement addresses. 192.168.1.4 is my load balancer or reverse proxy server.
  2. real_ip_header X-Forwarded-For; You need to define the request header field whose value will be used to replace the client address. The X-Real-IP and X-Forwarded-For parameters contain client’s real IP address. This header is usually set in your load balancer or client IP address.

You must restart or reload your nginx server:

$ sudo service nginx restart

OR

$ systemctl reload nginx

Verification

Before setting set_real_ip_from in nginx.conf:

$ sudo tail -f /var/log/nginx/access.log

Sample outputs:

192.168.1.4 - - [18/Jan/2017:20:34:02 +0000] "GET / HTTP/1.0" 200 700 "https://theos.in/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"

After setting set_real_ip_from in nginx.conf:

$ sudo tail -f /var/log/nginx/access.log
204.55.22.11 - - [18/Jan/2017:20:34:02 +0000] "GET / HTTP/1.0" 200 700 "https://theos.in/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment