Solving WordPress’s Inability to Obtain the Real IP Address When Using a CDN
I just enabled the comment email notification feature yesterday, “Beautify the WordPress Email Reply Style,” and discovered that the commenter’s IP address in the emails was actually incorrect. WordPress had obtained the IP address of a CDN node.
As a result, it became difficult to analyze the geographic distribution of website visitors, and WordPress’s built-in IP-based 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 Blog. I’m sharing it with you below.

Solution
Open the wp-config.php file in the WordPress root directory and add the following code at the very end of the file:
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$list = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$_SERVER['REMOTE_ADDR'] = $list[0];
}
Principle
The visitor’s IP address is recorded in the CDN’s HTTP headers. This code replaces WordPress’s IP variable with the value obtained from $_SERVER. The code above can be used with any CDN or reverse proxy, allowing the correct IP address to be obtained.
Comments
(0)No comments yet. Start the conversation.