On a regular web host, WordPress has no problems when display the right IP address of visitors, comments, etc. However, on some servers WordPress site will not display the correct IP address in the comments dashboard and other places.

Depending on the software installed on the server and how is it configured, the client IP address may not be forwarded. WordPress has no built-in option to forward client IP address so to fix an incorrect IP address in the WordPress we will need to edit wp-config.php file.

// Correct client IP address fix
if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { 
    $xff_ip = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ); 
    $_SERVER['REMOTE_ADDR'] = $xff_ip[0]; 
}

What’s is that Code Snippet?

When your WordPress website is behind an HTTP proxy or using a load balancer, an HTTP header called “X-Forwarded-For” is used to store all the IP addresses including the real client IP address in the chain.

By default, the IP addresses in the “X-Forwarded-For” HTTP header are comma separated and the first IP address in the chain is always the client IP address.

What we are doing with the above code snippet is taking all those IP addresses, exploding them into individual pieces and storing them in the $xff_ip array. Since the first IP address is related to the client, we can use the zero index and point it to REMOTE_ADDR within the $_SERVER array.

Categories: Blog

3 Comments

Leave a Reply

Avatar placeholder

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