WordPress client IP address, behind a proxy

At the museum, we’re running a site where we want people to comment but where we’re also sitting ducks for spam comments. Trouble is, the site is running behind a web proxy. That means that all the comments are seemingly from the same IP address, namely that of the proxy host. That, in turn prevents any meaningful spam detection.

I poked around the web a while, looking for a way to get the real IP addresses, and finally rolled my own solution.

It boils down to this. If you’re running behind an up-to-date apache server that’s doing the proxying for you, all of the incoming HTTP requests should have the X-Fowarded-For header set to the originating client’s IP address.

Once I verified that this is the case, I put this snippet of code into my functions.php file.

function m150_ip_fixup($s) {
  $headers = apache_request_headers();

  if (!empty($headers["X-Forwarded-For"])) {
    $_SERVER["REMOTE_ADDR"] = $headers["X-Forwarded-For"];
  }
  return $s;
}

add_action( 'pre_comment_on_post', 'm150_ip_fixup');

Now, comments get tagged with their original IP address.

Posted in Museum, Wordpress