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

My nginx server is behind a reverse proxy load balancer. How can I show the correct client IP address in nginx log files when nginx is behind a load balancer?

If you are using nginx behind reverse proxies, load balancer and HTTPS front-end such as HAProxy/Pound, you may find hard to log or get the real IP address.

Fig.01: HAproxy LB and log the real user’s IP in Nginx log file instead of the proxy server

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:

    real_ip_header    X-Forwarded-For;

Save and close the file.

  1. set_real_ip_from; Set trusted addresses that are known to send correct replacement addresses. 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
$ systemctl reload nginx


Before setting set_real_ip_from in nginx.conf:
$ sudo tail -f /var/log/nginx/access.log
Sample outputs: - - [18/Jan/2017:20:34:02 +0000] "GET / HTTP/1.0" 200 700 "" "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 - - [18/Jan/2017:20:34:02 +0000] "GET / HTTP/1.0" 200 700 "" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"

See also

🐧 Please support my work on Patreon or with a donation.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
1 comment… add one
  • vanoc Jul 28, 2020 @ 11:44


Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @