Expose Real IP Addresses in Cloudflare & Nginx
How to expose a users real IP address in Nginx logs when using Cloudflare. By default everything routed through Cloudflare shows up in your logs as a Cloudflare server IP.
When you use Cloudflare for DNS they route everything through their servers.
This means that you do not see you visitors real IP addresses in logs, but rather the Cloudflare server addresses.
Luckily it's very easy to use ngx_http_realip_module
and the list of IPs provided by Cloudflare to forward the original IP in the headers.
https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs
ngx_http_realip_module
ngx_http_realip_module
module must be built in your Nginx. Debian comes with this module by default so I didn't need to do anything.
sudo nginx -V
And check the output for 'ngx_http_realip_module'.
Create the conf file with IPs
Download the up to date list from here https://www.cloudflare.com/ips/
sudo nano /etc/nginx/cong.d/cloudflare-realip.conf
set_real_ip_from 173.245.48.0/20;
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 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
real_ip_header CF-Connecting-IP;
sudo systemctl nginx restart