Whitelist cloudflare Ips with ngx_http_realip_module enabled
I am using nginx website running cloudflare and want to block all requests that do not fall under the cloudflare.
I usually pick nginx IPs in nginx config and discard all others.
But I am executing ngx_http_realip_module, which sets the X-Forward-For Address (which is the real Ip from Visitor) as the request-IP and so the request is rejected.
Is there a way to make this whitelist work without deactivating ngx_http_realip_module? Also this whitelist should only apply to requests to nginx and not to other services.
Thank you in advance
source to share
The only solution I have come across can be done with nginx by itself, requires nginx version 1.9.7 or higher.
You can use ngx_http_geo_module to identify and block responses for any ip that are not cloud flares.
Using this geo-block.
geo $realip_remote_addr $cloudflare_ip {
default 0;
103.21.244.0/22 1;
103.22.200.0/22 1;
103.31.4.0/22 1;
104.16.0.0/12 1;
108.162.192.0/18 1;
131.0.72.0/22 1;
141.101.64.0/18 1;
162.158.0.0/15 1;
172.64.0.0/13 1;
173.245.48.0/20 1;
188.114.96.0/20 1;
190.93.240.0/20 1;
197.234.240.0/22 1;
198.41.128.0/17 1;
199.27.128.0/21 1;
2400:cb00::/32 1;
2405:8100::/32 1;
2405:b500::/32 1;
2606:4700::/32 1;
2803:f800::/32 1;
2c0f:f248::/32 1;
2a06:98c0::/29 1;
}
Then you can add this to your server block.
if ($cloudflare_ip != 1) {
return 444;
}
Terminates the connection for any connections not associated with $cloudflare_ip
.
This works because I am using $realip_remote_addr
a geo-block that retains the original address of the client when used real_ip_header CF-Connecting-IP
.
source to share