Okay, here’s a comprehensive article on how to find and use Cloudflare IP ranges, aiming for approximately 5000 words and covering various aspects in detail:
How to Find & Use Cloudflare IP Ranges: A Comprehensive Guide
Cloudflare is a ubiquitous content delivery network (CDN) and web security company. It sits between a website’s origin server and the visitors accessing that website. This intermediary position provides numerous benefits, including performance improvements (through caching and optimized routing), security enhancements (DDoS mitigation, Web Application Firewall), and increased reliability. However, this architecture also means that the IP addresses visitors see when accessing a Cloudflare-protected website are not the origin server’s IP addresses. Instead, they see Cloudflare’s IP addresses.
Understanding and managing Cloudflare’s IP ranges is crucial for a variety of network administration, security, and troubleshooting tasks. This guide provides a deep dive into finding, understanding, and utilizing these IP ranges effectively.
1. Why You Need Cloudflare IP Ranges
Before we delve into how to find the IP ranges, it’s essential to understand why you might need them. Here are several key scenarios:
- Allowlisting/Whitelisting: This is arguably the most common reason. If you’re running a server behind Cloudflare, you often need to configure your firewall, intrusion detection/prevention systems (IDS/IPS), or other security tools to allow traffic specifically from Cloudflare’s IP ranges. Without this, legitimate traffic proxied through Cloudflare might be blocked, rendering your website inaccessible. This is particularly important for preventing direct-to-origin attacks.
- Rate Limiting and Access Control: You might want to apply different rate limiting rules or access control policies to traffic coming from Cloudflare compared to direct traffic (if any direct traffic is even allowed). Knowing the IP ranges allows you to create these specific rules.
- Log Analysis and Security Auditing: When examining server logs, you’ll see Cloudflare IP addresses instead of the actual visitor IP addresses. While Cloudflare provides the original visitor IP in the
CF-Connecting-IP
header (more on this later), you might need the Cloudflare IP ranges for filtering, correlating events, or identifying potential attack patterns originating from within Cloudflare’s network (though this is extremely rare). - Geolocation and Traffic Routing: While not the primary use case, knowing the general geographic distribution of Cloudflare’s data centers and their associated IP ranges can be helpful in understanding traffic patterns and potentially optimizing routing configurations (though Cloudflare handles most of this automatically).
- Troubleshooting Network Connectivity: If you’re experiencing connectivity issues with a Cloudflare-protected website, knowing the IP ranges can help you pinpoint the source of the problem. You can use tools like
traceroute
orping
to test connectivity to specific Cloudflare IP addresses and identify potential network bottlenecks. - Preventing Circumvention: Some malicious actors might attempt to bypass Cloudflare’s protection by discovering and directly targeting your origin server’s IP address. By strictly limiting access to your origin server to only Cloudflare’s IP ranges, you significantly reduce the attack surface and prevent this circumvention.
- API Integrations: Certain API integrations with your server might require you to specify allowed IP ranges for security reasons. If those APIs are accessed through Cloudflare, you’ll need to provide Cloudflare’s IP ranges.
2. Methods for Finding Cloudflare IP Ranges
Cloudflare makes its IP ranges publicly available through several methods. It’s crucial to use official sources to ensure accuracy and avoid potential security risks. Here are the recommended methods:
-
Official Cloudflare Documentation (The Primary Source): Cloudflare maintains an up-to-date list of its IP ranges on its website. This is the most reliable and recommended source. You can find it here:
https://www.cloudflare.com/ips/
This page provides the IP ranges in several formats:
- Plain Text Lists: Separate lists for IPv4 and IPv6 ranges. These are suitable for copy-pasting into firewall rules or configuration files.
- JSON Format: A JSON object containing both IPv4 and IPv6 ranges. This is ideal for programmatic access and automated updates (more on this later).
_spf.cloudflare.com
(for Email): While not directly related to website traffic, this SPF record contains IP ranges used by Cloudflare’s email services.
-
API Access (for Automation): Cloudflare’s API provides a programmatic way to retrieve the IP ranges. This is the best approach for automated systems that need to regularly update firewall rules or other configurations. Here’s how you can do it:
-
Using
curl
(andjq
for JSON parsing):bash
curl -s https://www.cloudflare.com/ips-v4 | jq -r '.[]' # IPv4 ranges
curl -s https://www.cloudflare.com/ips-v6 | jq -r '.[]' # IPv6 ranges
The commandcurl -s
fetches the content, the pipe takes the results from thecurl
command, and thejq -r '.[]'
command extracts the IP address ranges.
* Using Python (with therequests
library):“`python
import requestsdef get_cloudflare_ips():
ipv4_url = “https://www.cloudflare.com/ips-v4”
ipv6_url = “https://www.cloudflare.com/ips-v6”try: ipv4_response = requests.get(ipv4_url) ipv4_response.raise_for_status() # Raise an exception for bad status codes ipv4_ranges = ipv4_response.text.splitlines() ipv6_response = requests.get(ipv6_url) ipv6_response.raise_for_status() ipv6_ranges = ipv6_response.text.splitlines() return ipv4_ranges, ipv6_ranges except requests.exceptions.RequestException as e: print(f"Error fetching Cloudflare IP ranges: {e}") return [], []
ipv4_ranges, ipv6_ranges = get_cloudflare_ips()
print(“IPv4 Ranges:”)
for ip_range in ipv4_ranges:
print(ip_range)print(“\nIPv6 Ranges:”)
for ip_range in ipv6_ranges:
print(ip_range)
“`This Python script fetches the IP ranges from the Cloudflare URLs, handles potential errors, and prints the results. You can easily modify this script to store the ranges in a file or integrate them into a larger system.
-
Other Programming Languages: You can use similar methods with other programming languages like Node.js, Java, Go, etc., using their respective HTTP client libraries.
-
-
Third-Party Tools and Scripts (Use with Caution): Various third-party tools and scripts claim to provide Cloudflare IP ranges. While some might be legitimate, it’s strongly recommended to stick to the official sources (Cloudflare’s website and API) to avoid using outdated or potentially malicious IP lists. If you choose to use a third-party tool, thoroughly vet its source and reputation.
-
dig
Command (Not Recommended for Comprehensive Lists): You can use thedig
command (Domain Information Groper) to query DNS records, but this is not a reliable way to obtain a complete list of Cloudflare’s IP ranges.dig
will typically only return a small subset of the IPs associated with a specific Cloudflare domain. It’s useful for quick checks or troubleshooting, but not for building a comprehensive allowlist.bash
dig +short cloudflare.com # Returns a few Cloudflare IPs
3. Understanding CIDR Notation
The Cloudflare IP ranges are provided in CIDR (Classless Inter-Domain Routing) notation. Understanding CIDR is essential for correctly interpreting and using these ranges. CIDR notation combines an IP address with a prefix length (the number after the slash). Here’s a breakdown:
- IP Address: The standard IPv4 or IPv6 address.
-
Prefix Length (Slash Notation): This number indicates how many bits of the IP address represent the network portion. The remaining bits represent the host portion.
-
Example:
192.0.2.0/24
192.0.2.0
: The base IP address./24
: The prefix length. This means the first 24 bits of the 32-bit IPv4 address define the network. The remaining 8 bits (32 – 24 = 8) are for host addresses within that network.- This represents a network with 28 = 256 possible addresses (although the first and last addresses are typically reserved). The range is from
192.0.2.0
to192.0.2.255
.
-
Example:
2606:4700:4700::/48
2606:4700:4700::
: The base IPv6 address (the::
represents a sequence of zero bits)./48
: The prefix length. The first 48 bits define the network.- This represents a very large network, as IPv6 addresses are 128 bits long.
-
Key CIDR Prefix Lengths to Remember:
/32
(IPv4): Represents a single IP address./24
(IPv4): A common network size, representing 256 addresses./16
(IPv4): A larger network, representing 65,536 addresses./128
(IPv6): Represents a single IPv6 address./64
(IPv6): A common network size./48
(IPv6): Another common network size, often used for larger allocations.
4. Implementing Cloudflare IP Ranges in Different Systems
The specific steps for using Cloudflare IP ranges depend on the system or tool you’re configuring. Here are examples for common scenarios:
-
Firewalls (iptables, firewalld, Windows Firewall, etc.):
-
iptables
(Linux):“`bash
Assuming you have the IP ranges in files: cloudflare_ipv4.txt and cloudflare_ipv6.txt
IPv4
while read -r ip_range; do
iptables -A INPUT -p tcp -m multiport –dports 80,443 -s “$ip_range” -j ACCEPT
done < cloudflare_ipv4.txtIPv6
while read -r ip_range; do
ip6tables -A INPUT -p tcp -m multiport –dports 80,443 -s “$ip_range” -j ACCEPT
done < cloudflare_ipv6.txtDrop all other traffic to ports 80 and 443
iptables -A INPUT -p tcp -m multiport –dports 80,443 -j DROP
ip6tables -A INPUT -p tcp -m multiport –dports 80,443 -j DROP
“`This script reads the IP ranges from the files and creates
iptables
rules to allow TCP traffic on ports 80 and 443 (HTTP and HTTPS) from those ranges. It then adds rules to drop all other traffic to those ports. Important: This is a simplified example. You should adapt it to your specific firewall configuration and security policies. Consider using a more robust firewall management tool if you have complex rules. -
firewalld
(Linux):“`bash
Create a new zone for Cloudflare
firewall-cmd –permanent –new-zone=cloudflare
firewall-cmd –reloadAdd IP ranges to the zone (using files as above)
while read -r ip_range; do
firewall-cmd –permanent –zone=cloudflare –add-source=”$ip_range”
done < cloudflare_ipv4.txtwhile read -r ip_range; do
firewall-cmd –permanent –zone=cloudflare –add-source=”$ip_range”
done < cloudflare_ipv6.txtAdd services to the zone (HTTP and HTTPS)
firewall-cmd –permanent –zone=cloudflare –add-service=http
firewall-cmd –permanent –zone=cloudflare –add-service=httpsReload firewalld
firewall-cmd –reload
``
firewalld` zone for Cloudflare, adds the IP ranges to that zone, and allows HTTP and HTTPS traffic from that zone.
This creates a dedicated -
Windows Firewall:
Windows Firewall uses a graphical interface (or PowerShell). You’ll need to create inbound rules:
- Open “Windows Defender Firewall with Advanced Security.”
- Click “Inbound Rules” and then “New Rule…”
- Select “Custom rule.”
- Choose “All programs” (or specify your web server program).
- Select “These IP addresses” under “Which remote IP addresses does this rule apply to?”
- Click “Add…” and enter each Cloudflare IP range (in CIDR notation) one by one. This is tedious, so consider using a script to automate this (see PowerShell example below).
- Allow the connection.
- Apply the rule to the appropriate profiles (Domain, Private, Public).
- Give the rule a descriptive name (e.g., “Cloudflare IPv4”).
- Repeat for IPv6 ranges.
PowerShell Script for Windows Firewall
“`powershell
Requires -RunAsAdministrator
IPv4 Ranges
$ipv4Ranges = Get-Content -Path “cloudflare_ipv4.txt”
foreach ($range in $ipv4Ranges) {
New-NetFirewallRule -DisplayName “Cloudflare IPv4 – $range” -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80,443 -RemoteAddress $range
}IPv6 Ranges
$ipv6Ranges = Get-Content -Path “cloudflare_ipv6.txt”
foreach ($range in $ipv6Ranges) {
New-NetFirewallRule -DisplayName “Cloudflare IPv6 – $range” -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80,443 -RemoteAddress $range
}“`
This PowerShell script reads the IP ranges from text files, then creates rules to allow inbound traffic on 80, 443.
-
-
Web Servers (Apache, Nginx):
-
Apache (
mod_remoteip
):Apache’s
mod_remoteip
module is designed to handle situations where the web server is behind a proxy (like Cloudflare). It allows you to replace the remote IP address in Apache’s logs and environment variables with the original visitor IP address provided by Cloudflare in theCF-Connecting-IP
header. You also need to configure it with Cloudflare’s IP ranges.-
Enable
mod_remoteip
:bash
sudo a2enmod remoteip
sudo systemctl restart apache2 -
Configure
httpd.conf
or a virtual host configuration file:apache
<IfModule remoteip_module>
RemoteIPHeader CF-Connecting-IP
# Add Cloudflare IP ranges
RemoteIPTrustedProxy 103.21.244.0/22
RemoteIPTrustedProxy 103.22.200.0/22
RemoteIPTrustedProxy 103.31.4.0/22
RemoteIPTrustedProxy 104.16.0.0/13
RemoteIPTrustedProxy 104.24.0.0/14
RemoteIPTrustedProxy 108.162.192.0/18
RemoteIPTrustedProxy 131.0.72.0/22
RemoteIPTrustedProxy 141.101.64.0/18
RemoteIPTrustedProxy 162.158.0.0/15
RemoteIPTrustedProxy 172.64.0.0/13
RemoteIPTrustedProxy 173.245.48.0/20
RemoteIPTrustedProxy 188.114.96.0/20
RemoteIPTrustedProxy 190.93.240.0/20
RemoteIPTrustedProxy 197.234.240.0/22
RemoteIPTrustedProxy 198.41.128.0/17
RemoteIPTrustedProxy 2400:cb00::/32
RemoteIPTrustedProxy 2405:8100::/32
RemoteIPTrustedProxy 2405:b500::/32
RemoteIPTrustedProxy 2606:4700::/32
RemoteIPTrustedProxy 2803:f800::/32
RemoteIPTrustedProxy 2a06:98c0::/29
RemoteIPTrustedProxy 2c0f:f248::/32
# ... Add all other ranges from https://www.cloudflare.com/ips/ ...
</IfModule>
This configuration tells Apache to trust theCF-Connecting-IP
header and to only consider it valid if the request originates from one of the specified Cloudflare IP ranges. Important: Make sure to include all the current IP ranges from Cloudflare’s official list. You can automate this by using a script to fetch the ranges and update the configuration file.
-
-
Nginx (
ngx_http_realip_module
):Nginx’s
ngx_http_realip_module
serves a similar purpose to Apache’smod_remoteip
.-
Ensure
ngx_http_realip_module
is compiled into Nginx: Most standard Nginx installations include this module. -
Configure
nginx.conf
or a virtual host configuration file:“`nginx
http {
# … other configurations …set_real_ip_from 103.21.244.0/22; set_real_ip_from 103.22.200.0/22; set_real_ip_from 103.31.4.0/22; set_real_ip_from 104.16.0.0/13; set_real_ip_from 104.24.0.0/14; set_real_ip_from 108.162.192.0/18; set_real_ip_from 131.0.72.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 162.158.0.0/15; set_real_ip_from 172.64.0.0/13; set_real_ip_from 173.245.48.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 190.93.240.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; set_real_ip_from 2400:cb00::/32; set_real_ip_from 2405:8100::/32; set_real_ip_from 2405:b500::/32; set_real_ip_from 2606:4700::/32; set_real_ip_from 2803:f800::/32; set_real_ip_from 2a06:98c0::/29; set_real_ip_from 2c0f:f248::/32; # ... Add all other ranges from https://www.cloudflare.com/ips/ ... real_ip_header CF-Connecting-IP; real_ip_recursive on; # ... other configurations ...
}
“`This configuration tells Nginx to trust the
CF-Connecting-IP
header and to recursively search for the real IP address if the request has passed through multiple proxies (though this is less common with Cloudflare). Again, ensure you include all the current Cloudflare IP ranges. Automate the updates for best results.
-
-
-
Cloud Platforms (AWS, Google Cloud, Azure, etc.):
Most cloud platforms provide their own firewall services (e.g., AWS Security Groups, Google Cloud Firewall Rules, Azure Network Security Groups). The process is generally similar to configuring a traditional firewall:
- Create a new security group/firewall rule.
- Specify inbound rules.
- For the source IP addresses, enter the Cloudflare IP ranges in CIDR notation.
- Allow traffic on the necessary ports (typically 80 and 443).
- Associate the security group/firewall rule with your instances or resources.
These cloud platforms often have APIs or command-line tools that allow you to automate the creation and updating of these rules.
-
Databases
If your database is only meant to communicate with your web server, then restrict database access to only your web server’s IP address. If however, your webserver is behind Cloudflare and you need to allow connections directly to your database, you’ll need to add Cloudflare’s IP ranges.-
MySQL, MariaDB:
sql
-- Grant access to a specific user from Cloudflare IP ranges
GRANT ALL PRIVILEGES ON your_database.* TO 'your_user'@'103.21.244.0/22' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON your_database.* TO 'your_user'@'103.22.200.0/22' IDENTIFIED BY 'your_password';
-- ... repeat for all Cloudflare IP ranges ...
FLUSH PRIVILEGES;
* PostgreSQL:Modify the
pg_hba.conf
file (usually located in the PostgreSQL data directory). Add lines like these:“`
TYPE DATABASE USER ADDRESS METHOD
host all all 103.21.244.0/22 md5
host all all 103.22.200.0/22 md5
# … repeat for all Cloudflare IP ranges …
host all all ::1/128 md5 #This may already be configured“`
And restart PostgreSQL.
-
-
Other Systems (IDS/IPS, Load Balancers, etc.): Refer to the documentation for your specific system. The general principle is the same: you need to configure the system to recognize and allow traffic from Cloudflare’s IP ranges.
5. Automating IP Range Updates
Cloudflare’s IP ranges can change, although it’s relatively infrequent. To ensure your configurations remain up-to-date and your website remains accessible, it’s highly recommended to automate the process of fetching and updating the IP ranges. Here are some strategies:
-
Cron Jobs (Linux): You can create a cron job that runs a script (like the Python script provided earlier) at regular intervals (e.g., daily or weekly). This script can fetch the latest IP ranges, compare them to the current configuration, and update the firewall rules or other settings if necessary.
“`bash
Example crontab entry (runs daily at 3:00 AM)
0 3 * * * /path/to/your/script.py
“` -
Scheduled Tasks (Windows): Similar to cron jobs, you can use Windows Task Scheduler to run a PowerShell script (like the one provided earlier) at regular intervals.
-
Configuration Management Tools (Ansible, Chef, Puppet, SaltStack): These tools are designed for automating infrastructure management. You can use them to define the desired state of your firewall rules (including Cloudflare’s IP ranges) and automatically apply any necessary changes. This is a more robust and scalable approach for larger deployments.
-
Cloud Platform-Specific Solutions: Many cloud platforms offer services or features that can help with this. For example, AWS Lambda can be used to run a script that fetches the IP ranges and updates AWS Security Groups.
-
Custom Scripts with Alerting: You can enhance your scripts to include alerting. If the script detects a change in Cloudflare’s IP ranges, it can send a notification (e.g., email, Slack message) to alert you of the change and potentially trigger an automated update process.
Example: Automated Update Script (Python with iptables
and alerting):
“`python
import requests
import subprocess
import smtplib
from email.mime.text import MIMEText
Configuration
CLOUDFLARE_IPV4_URL = “https://www.cloudflare.com/ips-v4”
CLOUDFLARE_IPV6_URL = “https://www.cloudflare.com/ips-v6”
IPV4_FILE = “/etc/cloudflare_ipv4.txt” # File to store current IPv4 ranges
IPV6_FILE = “/etc/cloudflare_ipv6.txt” # File to store current IPv6 ranges
EMAIL_SENDER = “[email protected]”
EMAIL_RECEIVER = “[email protected]”
EMAIL_SUBJECT = “Cloudflare IP Ranges Updated”
SMTP_SERVER = “smtp.example.com”
SMTP_PORT = 587
SMTP_USERNAME = “your_username”
SMTP_PASSWORD = “your_password”
def get_current_ips(filename):
try:
with open(filename, “r”) as f:
return set(f.read().splitlines())
except FileNotFoundError:
return set()
def save_ips(filename, ips):
with open(filename, “w”) as f:
for ip_range in ips:
f.write(ip_range + “\n”)
def update_iptables(ip_type, new_ips, old_ips):
iptables_cmd = “iptables” if ip_type == “ipv4” else “ip6tables”
# Remove old rules
for ip_range in old_ips - new_ips:
subprocess.run([iptables_cmd, "-D", "INPUT", "-p", "tcp", "-m", "multiport", "--dports", "80,443", "-s", ip_range, "-j", "ACCEPT"], check=False)
# Add new rules
for ip_range in new_ips - old_ips:
subprocess.run([iptables_cmd, "-A", "INPUT", "-p", "tcp", "-m", "multiport", "--dports", "80,443", "-s", ip_range, "-j", "ACCEPT"], check=True)
def send_email(message):
try:
msg = MIMEText(message)
msg[“Subject”] = EMAIL_SUBJECT
msg[“From”] = EMAIL_SENDER
msg[“To”] = EMAIL_RECEIVER
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls() # Use TLS encryption
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.sendmail(EMAIL_SENDER, EMAIL_RECEIVER, msg.as_string())
print("Email notification sent successfully.")
except Exception as e:
print(f"Error sending email: {e}")
def main():
ipv4_ranges, ipv6_ranges = [],[]
try:
ipv4_response = requests.get(CLOUDFLARE_IPV4_URL)
ipv4_response.raise_for_status() # Raise an exception for bad status codes
ipv4_ranges = ipv4_response.text.splitlines()
ipv6_response = requests.get(CLOUDFLARE_IPV6_URL)
ipv6_response.raise_for_status()
ipv6_ranges = ipv6_response.text.splitlines()
except requests.exceptions.RequestException as e:
print(f"Error fetching Cloudflare IP ranges: {e}")
exit(1)
new_ipv4_ips = set(ipv4_ranges)
new_ipv6_ips = set(ipv6_ranges)
current_ipv4_ips = get_current_ips(IPV4_FILE)
current_ipv6_ips = get_current_ips(IPV6_FILE)
if new_ipv4_ips != current_ipv4_ips:
print("IPv4 ranges have changed. Updating iptables...")
update_iptables("ipv4", new_ipv4_ips, current_ipv4_ips)
save_ips(IPV4_FILE, new_ipv4_ips)
send_email(f"Cloudflare IPv4 ranges have been updated. New ranges:\n{new_ipv4_ips}")
if new_ipv6_ips != current_ipv6_ips:
print("IPv6 ranges have changed. Updating iptables...")
update_iptables("ipv6", new_ipv6_ips, current_ipv6_ips)
save_ips(IPV6_FILE, new_ipv6_ips)
send_email(f"Cloudflare IPv6 ranges have been updated. New ranges: \n{new_ipv6_ips}")
if name == “main“:
main()
“`
This script:
- Fetches the latest IP ranges from Cloudflare.
- Reads the currently configured IP ranges from files (
/etc/cloudflare_ipv4.txt
,/etc/cloudflare_ipv6.txt
). - Compares the new and current IP ranges.
- If there are changes:
- Updates
iptables
rules (removes old rules, adds new rules). - Saves the new IP ranges to the files.
- Sends an email notification.
- Updates
- Handles errors (e.g., network issues,
iptables
errors).
This is a more complete example that demonstrates a robust approach to automating IP range updates. You would run this script using a cron job. Important: Adjust the file paths, email settings, and iptables
commands to match your specific environment and security policies. Test thoroughly before deploying to a production environment. Consider adding error logging for better troubleshooting.
6. Retrieving the Real Visitor IP Address
Because Cloudflare acts as a reverse proxy, your web server will see Cloudflare’s IP addresses as the source of incoming requests, not the actual visitor’s IP address. Cloudflare provides the original visitor’s IP address in several HTTP headers:
CF-Connecting-IP
: This is the most reliable and recommended header to use. It contains the original visitor’s IP address.True-Client-IP
: This header is also provided by Cloudflare and serves the same purpose asCF-Connecting-IP
. You can generally use either one.X-Forwarded-For
: This is a standard HTTP header used by many proxies. It can contain a list of IP addresses if the request has passed through multiple proxies. With Cloudflare, the leftmost IP address in theX-Forwarded-For
header should be the original visitor’s IP address. However,X-Forwarded-For
can be spoofed more easily thanCF-Connecting-IP
orTrue-Client-IP
, so it’s less reliable unless you’ve specifically configured your web server to trust only Cloudflare’s IP ranges (as shown in the Apache and Nginx examples earlier).
How to Access These Headers:
-
Web Server Configuration (Recommended): The best approach is to configure your web server (Apache, Nginx) to automatically replace the remote IP address with the value from the
CF-Connecting-IP
header (as shown in the examples in Section 4). This ensures that your server logs and application code see the correct visitor IP address. -
Application Code: If you need to access the visitor IP address within your application code (e.g., PHP, Python, Node.js), you can read the appropriate HTTP header.
-
PHP:
php
$visitor_ip = $_SERVER['HTTP_CF_CONNECTING_IP']; -
Python (Flask example):
“`python
from flask import Flask, requestapp = Flask(name)
@app.route(“/”)
def index():
visitor_ip = request.headers.get(‘CF-Connecting-IP’)
return f”Your IP address is: {visitor_ip}”
“` -
Node.js (Express example):
“`javascript
const express = require(‘express’);
const app = express();app.get(‘/’, (req, res) => {
const visitorIp = req.headers[‘cf-connecting-ip’];
res.send(Your IP address is: ${visitorIp}
);
});app.listen(3000, () => {
console.log(‘Server listening on port 3000’);
});
* **.htaccess**
apache
You can modify the environment variables with `.htaccess` if you do not have access to modify the main Apache configuration:
RewriteEngine On
RewriteCond %{HTTP:CF-Connecting-IP} ^(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})$
RewriteRule ^(.*)$ – [E=REMOTE_ADDR:%1]
“`
7. Common Mistakes and Troubleshooting -
-
Using Outdated IP Lists: One of the most common mistakes is using outdated IP lists found on unofficial websites or forums. Always use the official Cloudflare sources.
- Incorrect CIDR Notation: Double-check the CIDR notation when configuring firewall rules. A typo (e.g.,
/23
instead of/24
) can significantly change the range of allowed IP addresses. - Forgetting IPv6: If your website and server support IPv6, you must include Cloudflare’s IPv6 ranges in your allowlist