How to get real IP of user in WordPress when using NginX as proxy

If your wordpress instance is behind an Nginx Proxy, by default you won’t get their real IP. To fix this issue, you will need to update your proxy configuration with the following details:

server {
	listen 443 ssl;
	ssl_certificate /cert/;
	ssl_certificate_key /cert/;
	error_log  /var/log/nginx/error.log;
	access_log /var/log/nginx/access.log;
	resolver valid=5s;
	set $upstream http://webserver;
	location / {
		proxy_set_header  Host $host;
		proxy_set_header  X-Real-IP $remote_addr;
		proxy_set_header  X-Forwarded-For $remote_addr; 
		proxy_set_header  X-Forwarded-Host $remote_addr;
		proxy_pass $upstream;

Once updated, restart your nginx service and add the following code in your wp-config.php file.

if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
  $http_x_headers = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );

  $_SERVER['REMOTE_ADDR'] = $http_x_headers[0];

You should now see your visitor’s IP.

Leave a Reply

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