Real IP's for cloudflare proxied traffic on nginx

We've been under attack, we migrated our domain to Cloudflare and now we just see cloudflare node ips connecting to our servers and applications. Lets configure nginx to display real ones.

Cloudflare adds the CF-Connecting-IP header tag to all requests with our real visitor's ip. But we're not trusting anybody adding the tag to their request.

Luckily there's a list of Cloudflare's ip ranges you'll find there the list on plain-text format.

Let's make dirty script to keep the list updated:

#!/bin/sh
TARGET=/etc/nginx/cloudflare

echo '# Cloudflare ip list' > $TARGET

for ip in `curl -s https://www.cloudflare.com/ips-v4; curl -s https://www.cloudflare.com/ips-v6`

   do  echo set_real_ip_from $ip\; >> $TARGET

done

echo 'real_ip_header CF-Connecting-IP;' >> $TARGET

# reload nginx
/etc/init.d/nginx reload

On Debian we can save-it to /etc/cron.daily/ a gave-it execution perms.

Then we tell nginx to include the file:

http {
   [...]
   include /etc/nginx/cloudflare;
   [...]
}

From now on nginx will display the real ip to our logs and applications.

© 2019 Joan Pérez i Cauhé. All rights reserved.