Skip to content

Instantly share code, notes, and snippets.

@Rhilip
Forked from todiadiyatmo/nginx cloudflare
Last active July 23, 2018 21:28
Show Gist options
  • Save Rhilip/bed10d4d37be422a1a1f191e4f5a46ec to your computer and use it in GitHub Desktop.
Save Rhilip/bed10d4d37be422a1a1f191e4f5a46ec to your computer and use it in GitHub Desktop.
nginx cloudflare
# Conection Limit
# http://serverfault.com/questions/177461/how-to-rate-limit-in-nginx-but-including-excluding-certain-ip-addresses
# http://gadelkareem.com/2015/01/18/limiting-connections-requests-wordpress-nginx/
geo $whitelist {
default 0;
# CIDR in the list below are not limited ( 1 )
127.0.0.1/32 1;
}
map $whitelist $limit {
0 $binary_remote_addr;
1 "";
}
# The directives below limit concurrent connections from a
# non-whitelisted IP address to five
limit_conn_zone $limit zone=conlimit:30m;
limit_conn_zone $limit zone=conlimit_php:30m;
limit_conn conlimit 40;
limit_conn_log_level warn; # logging level when threshold exceeded
limit_conn_status 503; # the error code to return
# Limit Req Non - PHP
limit_req_zone $limit zone=reqlimit:30m rate=5r/s;
limit_req zone=reqlimit burst=10;
# Limit Req PHP
limit_req_zone $limit zone=reqlimit_php:30m rate=1r/s;
limit_req_log_level warn;
limit_req_status 503;
# Location VirtualHost
limit_req zone=reqlimit_php burst=4;
limit_conn conlimit_php 10;
#Cloudflare
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 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
# use any of the following two
real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For;
#!/bin/bash
cloudflare_real_ip_conf='/usr/local/nginx/conf/cloudflare_ip.conf'
echo "#Cloudflare" > ${cloudflare_real_ip_conf};
for i in `curl https://www.cloudflare.com/ips-v4`; do
echo "set_real_ip_from $i;" >> ${cloudflare_real_ip_conf};
done
for i in `curl https://www.cloudflare.com/ips-v6`; do
echo "set_real_ip_from $i;" >> ${cloudflare_real_ip_conf};
done
echo "" >> /usr/local/nginx/conf/cloudflare_ip.conf;
echo "# use any of the following two" >> ${cloudflare_real_ip_conf};
echo "real_ip_header CF-Connecting-IP;" >> ${cloudflare_real_ip_conf};
echo "#real_ip_header X-Forwarded-For;" >> ${cloudflare_real_ip_conf};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment