Yesterday, right after enabling the comment email notification feature “Beautify WordPress Email Reply Styles,” I discovered that the commenter’s IP address in the email was incorrect. WordPress had retrieved the IP address of the CDN node.

As a result, it became difficult to analyze the geographical distribution of website visitors, and WordPress’s built-in IP comment-blocking feature would also stop working, so I wanted to solve the problem. I searched online for related information and later found the perfect solution on Huansha’s blog. I’ll share it with you below.

Image

Solution

Open the wp-config.php file in the WordPress root directory and add the following code at the very bottom of the file:

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

Principle

The CDN’s HTTP headers contain the visitor’s IP address. That code replaces the IP variable in WordPress with the value retrieved through $_SERVER. The code above can be used with any CDN or reverse proxy, and the correct IP address can be obtained.