WordPress Comments and Varnish

After along time searching for the answer to fix my issue of where users post a comment and the IP address in the comment is of my Varnish server not the clients IP address who made the comment. Well this issue is now resolved after finding this post! http://theterminaladmin.com/wordpress-comments-and-varnish/

Ironically I couldn’t post a comment of gratitude onto his word-press site as I got a submitting error.

Just in-case is website disipears his post was the following:

While setting up this site I ran into an issue where comments posted were reporting the IP address as 127.0.0.1. This looked to be coming from Varnish and luckily, is fixable by editing two WordPress files.

The first is $document_root/wp-includes/pluggable.php. Add the following lines anywhere in the file:

if ( !function_exists('get_user_real_ip') ) { function get_user_real_ip() { $userip = ( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; return $userip; } }

The second is $document_root/wp-includes.comment.php:

Replace the following line:

 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );

With:

 $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',get_user_real_ip() );

A simple fix but it works. You may need to re-apply this if you update/re-install WordPress but that is trivial at this point considering how easy it is :)

One thought on “WordPress Comments and Varnish

  1. A solution which does not imply hacking the code:

    Create a file call, for instance, /usr/share/php/real-ip.php with the following contents:

    Then add it to your php.ini file, search for:
    auto_prepend_file =
    And replace with:
    auto_prepend_file = /usr/share/php/real-ip.php

    It works like a Charm!

Leave a Reply

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