How to store Cloudflare IP as an additional FastCGI parameter in Nginx?

Jaw.sh asked:

I need to be able to know the Cloudflare IP for connections made to my server.

This is so I can determine if a connection is made through Tor. To do that, I need to send the tool the IP that the client CONNECTED TO. That is NOT my server’s IP, that is the IP of the Cloudflare entry proxy, which is why I’m trying to pass the Cloudflare IP through fastcgi.
https://www.torproject.org/projects/tordnsel.html.en

I have a block that looks like this:

# Preserve Cloudflare IP
fastcgi_param CF-Proxy-IP $remote_addr;
fastcgi_param TEST "abc123";

# CloudFlare
set_real_ip_from 199.27.128.0/21;
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/12;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
real_ip_header CF-Connecting-IP;

But it’s not going through and the dummy headers I set do not get seen in phpinfo(). I’m not sure what else I can do because after the real_ip_header goes through, all original CF data is lost.

My answer:


When you use the nginx real ip module, nginx places the actual connecting IP address in the $realip_remote_addr variable when it does the IP address substitution. So you can pass this to your application by setting the header:

fastcgi_param CF-Proxy-IP $realip_remote_addr;

This variable requires nginx 1.9.7 or later.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.