Skip to content

Instantly share code, notes, and snippets.

@sanmai
Last active August 26, 2017 02:21
Show Gist options
  • Save sanmai/158f6439da91d6a0d8507b68d3b042ec to your computer and use it in GitHub Desktop.
Save sanmai/158f6439da91d6a0d8507b68d3b042ec to your computer and use it in GitHub Desktop.
Generate nginx config for use with Cloudflare
  1. Put update-cf.sh to /etc/nginx/;
  2. chmod +x /etc/nginx/update-cf.sh
  3. Add an entry in crontab to call it weekly: @weekly sleep $RANDOM; /etc/nginx/update-cf.sh
  4. Add /etc/nginx/cloudflare.conf
  5. Use it.

Example:

server {
    server_name www.example.com;
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    include cloudflare.conf;

    limit_rate_after 1k;
    if ($http_referer = "") {
        set $limit_rate 4k;
    }
    if ($http_user_agent = "") {
        set $limit_rate 2k;
    }
    if ($cloudflare) {
        set $limit_rate 100m;
    }
    # and so forth
}
# this file will be generated - in conf.d/
geo $cloudflare {
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;
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;
}
# this file will be generated
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;
real_ip_header CF-Connecting-IP;
include cloudflare-ip.conf;
#!/bin/bash
# put this file into /etc/nginx
set -e
cd $(dirname $0)
ips="$(curl -s https://www.cloudflare.com/ips-v4) $(curl -s https://www.cloudflare.com/ips-v6)"
exec 1<&-
exec 1>cloudflare-ip.conf
for ip in $ips
do
echo "set_real_ip_from $ip;"
done
exec 1<&-
exec 1>conf.d/cloudflare-geo.conf
echo "geo \$cloudflare {"
echo " default 0;"
for ip in $ips
do echo " $ip 1;"
done
echo "}"
exec 1<&-
service nginx reload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment