Find the Real IP Address of Commentors For Enterprise WordPress Sites
Recently, this site was moved to a virtual environment similar to being in a load-balanced (enterprise) situation… and the IP address of my commentors vanished!
Actually, they didn’t vanish, but they all matched the IP of my proxy.
(If you’re in standard shared hosting this post does not apply to you.)
From the hosting side there was nothing I could do about that. This situation affects anyone hosted in a large scale situation which includes countless enterprise-level sites.
While I deeply believe that IP handling for those behind a proxy or load-balancer needs to be patched at the WordPress core level… it has not been (and they say it won’t be).
Here’s how I fixed comment IP issue:
1. First, download a copy of the patched comments.php that Naicin wrote and upload it to your host. It replaces the original comments.php file. (You will find a download original format link at the very bottom of that page.)
This file sets REMOTE_ADDR which we will re-assign using our wp-config file.
2. Second, we need to add some code to our wp-config.php file.
Nacin supplied an example code here in comment #40. However, this is hosting specific and must be adjusted for your site.
if ( ! empty( $_SERVER[‘HTTP_X_FORWARDED_FOR’] ) && preg_match( ‘/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/’, $_SERVER[‘HTTP_X_FORWARDED_FOR’] ) ) $_SERVER[‘REMOTE_ADDR’] = $_SERVER[‘HTTP_X_FORWARDED_FOR’];
In my particular case, because the proxy was returning 10.10.0.1 consistently…
We tested with this code:
if ( ! empty( $_SERVER[‘HTTP_X_FORWARDED_FOR’] ) && $_SERVER[“REMOTE_ADDR”] == “10.10.0.1”) { print “test\n”; $iptest = “79.117.236.67, 173.245.51.112”; $ipexplode = explode(“,”, $iptest); print “{$ipexplode[0]}\n
“; $forwardip = explode(“,”, $_SERVER[‘HTTP_X_FORWARDED_FOR’]); print “Forward IP: {$forwardip[0]}
\n”;}
And our final code used in the wp-config.php file on this live site is:
if ( ! empty( $_SERVER[‘HTTP_X_FORWARDED_FOR’] ) && $_SERVER[“REMOTE_ADDR”] == “10.10.0.1”) { $forwardip = explode(“,”, $_SERVER[‘HTTP_X_FORWARDED_FOR’]); $_SERVER[‘REMOTE_ADDR’] = $forwardip[0];}
Using this patched comments.php and wp-config.php file allowed me to successfully resume seeing my commentors IP addresses… which is a vital part of spam filtering!
This patch works great. However, any WordPress upgrade that alters the comments.php file will “undo” it and I’ll need to upload the patched file again. Something to keep an eye on.
Load-balanced/Proxied sites are common in a corporate and enterprise environment and if WordPress wishes to continue to grow in that sphere this update to core needs made.
PS: Please be careful copy/pasting these code snippets as they may contain stray hidden characters. Be sure to paste them into a plain text editor like notepad before checking and using.
Comments on this article are closed.