Apache Show Real IP Address when using CloudFlare

When using Apache web server behind cloudflare, apache logs show cloudflare IP address instead of real visitor IP address. To show actual visitor IP address, you can enable remoteip apache module.

On Debian/Ubuntu server:

sudo a2enmod remoteip


On RHEL/CentOS/Fedora, it is Usually enabled by default; check with:

httpd -M | grep remoteip

Cloudflare publishes its IP ranges here:

IPv4: https://www.cloudflare.com/ips-v4
IPv6: https://www.cloudflare.com/ips-v6

Create file

vi /etc/apache2/conf-enabled/remoteip.conf

Add following content:

RemoteIPHeader CF-Connecting-IP

RemoteIPTrustedProxy 173.245.48.0/20
RemoteIPTrustedProxy 103.21.244.0/22
RemoteIPTrustedProxy 103.22.200.0/22
RemoteIPTrustedProxy 103.31.4.0/22
RemoteIPTrustedProxy 141.101.64.0/18
RemoteIPTrustedProxy 108.162.192.0/18
RemoteIPTrustedProxy 190.93.240.0/20
RemoteIPTrustedProxy 188.114.96.0/20
RemoteIPTrustedProxy 197.234.240.0/22
RemoteIPTrustedProxy 198.41.128.0/17
RemoteIPTrustedProxy 162.158.0.0/15
RemoteIPTrustedProxy 104.16.0.0/13
RemoteIPTrustedProxy 104.24.0.0/14
RemoteIPTrustedProxy 172.64.0.0/13
RemoteIPTrustedProxy 131.0.72.0/22

RemoteIPTrustedProxy 2400:cb00::/32
RemoteIPTrustedProxy 2606:4700::/32
RemoteIPTrustedProxy 2803:f800::/32
RemoteIPTrustedProxy 2405:b500::/32
RemoteIPTrustedProxy 2405:8100::/32
RemoteIPTrustedProxy 2a06:98c0::/29
RemoteIPTrustedProxy 2c0f:f248::/32

Restart apache web server with

service apache2 restart

Script to auto update cloudflare IPs:

#!/bin/bash
# Script: update-cloudflare-ips.sh

CF_IPV4_URL="https://www.cloudflare.com/ips-v4"
CF_IPV6_URL="https://www.cloudflare.com/ips-v6"
OUTPUT_FILE="/etc/apache2/conf-enabled/remoteip.conf"

echo "# Cloudflare IP Ranges (Auto-generated $(date))" > $OUTPUT_FILE
echo "RemoteIPHeader CF-Connecting-IP" >> $OUTPUT_FILE

echo "# IPv4" >> $OUTPUT_FILE
curl -s $CF_IPV4_URL | while read line; do
    echo "RemoteIPTrustedProxy $line" >> $OUTPUT_FILE
done

echo "# IPv6" >> $OUTPUT_FILE
curl -s $CF_IPV6_URL | while read line; do
    echo "RemoteIPTrustedProxy $line" >> $OUTPUT_FILE
done

Comments

Leave a Reply

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