Configure WordPress to report real IP when behind a reverse proxy

When hosting WordPress behind a reverse proxy, such as Cloudflare or a load balancer, the server only receives the IP of the proxy instead of the IPs of individual visitors. This can complicate tasks like tracking visitor information or setting up IP-based security rules, as every client appears to be coming from the proxy’s IP address.

Fortunately, there’s a simple way to ensure WordPress accurately identifies each client’s IP.

To display the correct client IP in WordPress, add the following code to your wp-config.php file:

if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
	$list = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
	$_SERVER['REMOTE_ADDR'] = $list[0];
}

How It Works

The HTTP_X_FORWARDED_FOR header is commonly used by reverse proxies to pass along the original client’s IP address. This header can contain a list of IPs if the request has passed through multiple proxies. By taking the first IP in this list (the original client IP), we set $_SERVER['REMOTE_ADDR'] to match the true client IP, ensuring that WordPress logs and uses this IP instead of the proxy’s IP.

Why This Matters

If WordPress and its plugins don’t receive the correct client IP, it can lead to issues like incorrect geolocation, failure to block abusive IPs, and inaccurate analytics. With this configuration, WordPress interprets and logs each visitor’s actual IP address, helping plugins and security features function accurately.