Show X-Forwarded-For IP in Apache
When apache is running behind the proxy server it shows the IP of the proxy server as visitor IP. To fix this, you need to enable Apache module remoteip.
https://httpd.apache.org/docs/2.4/mod/mod_remoteip.html
On Ubuntu/Debian, this can be enabled with the command
1 |
a2enmod remoteip |
Now create file
1 |
vi /etc/apache2/conf-available/remoteip.conf |
Add
1 2 |
RemoteIPHeader X-Forwarded-For RemoteIPTrustedProxy IP_OF_YOUR_PROXY_SERVER_HERE |
IP_OF_YOUR_PROXY_SERVER_HERE = repace with your proxy server. This can be any proxy server like haproxy, nginx, etc.. If you have more than one proxy server, use IPs separated by space.
If your proxy IP is internal, use RemoteIPInternalProxy instead of RemoteIPTrustedProxy. On a server running varnish, RMOTE_ADDR shows 127.0.0.1 (varnish IP). To fix this, I used following
1 2 |
RemoteIPHeader CF-Connecting-IP RemoteIPInternalProxy 127.0.0.1 |
CF-Connecting-IP is because the site was behind cloudflare. Use X-Forwarded-For instead of CF-Connecting-IP if not using cloudflare.
Enable config with
1 |
a2enconf remoteip |
To get Apache Logs to show real Visitor IP, replace %h with %a in LogFormat.
On Ubuntu
1 |
vi /etc/apache2/apache2.conf |
Find
1 |
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined |
Replace with
1 |
LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined |
Restart Apache with
1 |
systemctl restart apache2 |
Now apache/php will show proper visitor IP instead of proxy server IP.