In this tutorial, I will explain how to get the real IP address of visitors using CloudFlare services and an Nginx web server.
What I will explain to you in this tutorial is valid when Nginx is used as a front-end web server or as a reverse proxy.
By default, when using CloudFlare in Proxy mode, the IP address seen by the Web server is the address of the CloudFlare server that was used and therefore level of the Nginx logs, we end up with the IPs of the CloudFlare servers.
This situation is awkward when:
- Logs are used to generate statistics
- We use a protection solution like Crowdsec or Fail2ban, because we block the CloudFlare server and not the “attacker”.
Retrieve the visitor’s real IP address
To retrieve the visitor’s IP address, we will modify the configuration file /etc/nginx/nginx.conf
.
Start by saving the file /etc/nginx/nginx.conf
:
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak001
Now we will create in the /etc/nginx folder a file named CloudfFare which contains the parameters:
Create the file:
sudo touch /etc/nginx/cloudflare
Edit file:
sudo nano /etc/nginx/cloudflare
Paste the content below, which will allow you to change CloudFlare’s IP to the visitor’s IP:
#Cloudflare ip addresses
# - IPv4
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/12;
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;
# - IPv6
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 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
real_ip_header CF-Connecting-IP;
Now open the file /etc/nginx/nginx.conf
to indicate to include the file cloudflare
.
sudo nano /etc/nginx/nginx.conf
In the section http{ ... }
add :
# Cloudflare Real IP visitors
include /etc/nginx/cloudflare;
Check Nginx configuration:
sudo nginx -t
If there is no error, restart Nginx to take it into account:
sudo systemctl restart nginx
Now check the logs (access), the real ip of the visitor must be captured.
To retrieve IP addresses from Cloudflare, they are available here:
- IPv4 : https://www.cloudflare.com/ips-v4
- IPv6 : https://www.cloudflare.com/ips-v6