Setting the correct forwarded IP address in WordPress Stream plugin

If you are using the WordPress Stream plugin and have a reverse proxy like Varnish in front of it, you might be seeing the IP of your Varnish machines rather than the client IP. This snippet lets you set the proper IP address that Varnish or other reverse proxies forward.

This code only works for Apache. If you are running Nginx you will need the getallheaders polyfill.

//Add proper forwarded IP to log records
add_filter('wp_stream_record_array', function($record) {
   //Get proper IP
   if(function_exists('getallheaders')) {
      $headers = getallheaders();

      //Exchange IP if header set
      if(isset($headers['X-Forwarded-For'])) {
        $record['ip'] = filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP);
      }
    }

    return $record;
});

Leave a Reply

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

Markdown is allowed in comments.