Make Piwik Detect the Header X-Forwarded-For or X-Real-IP (that for example nginx can set as reverse proxy for your site)

If you run a Piwik installation behind an nginx reverse proxy, you have to change a bit of your configuration because the remote IP has changed to that of the nginx reverse proxy.

For example if your nginx reverse proxy configurations includes:

proxy_set_header HOST $host;
proxy_set_header X-Real-IP  $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Then nginx adds two headers with IPs: X-Real-IP and X-Forwarded-For to the request for Piwik. First I chose X-Forwarded-For as logging for the IP but actually X-Real-IP is safer because any user can send bad X-Forwarded-For headers. So all you have to do is to add some lines to the [General] section of config/config.ini.php, your Piwik configuration file:


; Fix for nginx proxys or similar:
;proxy_client_headers[] = HTTP_X_FORWARDED_FOR
proxy_client_headers[] = HTTP_X_REAL_IP

Testing the Header

If you want to check if you header gets propagated through to you web server and is handled correctly, do:

curl -v --header "X-Real-IP: ::ffff:" ""

(Note that this request will not appear in your Piwik log, as curl will not run any JavaScript etc.)