Skip to content

Instantly share code, notes, and snippets.

@ilyaevseev
Created May 30, 2018 13:59
Show Gist options
  • Save ilyaevseev/b08861034a59ff3a48fa353761715df4 to your computer and use it in GitHub Desktop.
Save ilyaevseev/b08861034a59ff3a48fa353761715df4 to your computer and use it in GitHub Desktop.
/etc/cron.daily/Cloudflare-Nginx-RealIP-Update -- update Nginx config by list of Cloudflare frontends.
#!/bin/sh -e
# https://support.cloudflare.com/hc/en-us/articles/200170706-How-do-I-restore-original-visitor-IP-with-Nginx-
STATEDIR="${1:-/var/log/${0##*/}}"
mkdir -p "$STATEDIR"
CONFDIR="${2:-/etc/nginx/conf.d}"
test -d "$CONFDIR" || { echo "missing confdir: $CONFDIR" 1>&2; exit 1; }
V4="$STATEDIR/v4.lst"
V6="$STATEDIR/v6.lst"
wget -qO "$V4.$$" https://www.cloudflare.com/ips-v4
wget -qO "$V6.$$" https://www.cloudflare.com/ips-v6
ok=
test -s "$V4" && diff -q "$V4" "$V4.$$" >/dev/null 2>&1 && ok="x"
test -s "$V6" && diff -q "$V6" "$V6.$$" >/dev/null 2>&1 && ok="x$ok"
test "$ok" = "xx" && exit 0
mv "$V4.$$" "$V4"
mv "$V6.$$" "$V6"
awk '{ print "set_real_ip_from",$1,";" } END { print "real_ip_header CF-Connecting-IP;" }' "$V4" "$V6" > "$CONFDIR/000-Cloudflare-SetRealIP.conf"
nginx -t
nginx -s reload
## END ##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment