Nginx: get the visitor’s real IP with CloudFlare

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:

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 :
  • IPv6 :