Back to Articles

Caddy and Cloudflare

A basic Caddy example for setting the trusted proxy ip addresses for Cloudflare. To make this scalable you'd likely want to create a template with the reverse_proxy statement (and any other directives you need) and then import it into each virtual host definition.

www.example.com { 
        reverse_proxy upstream.server:443 {
                trusted_proxies 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22
        }
}

Template based definition:

(example_backend)
{
        reverse_proxy upstream.server:443 {
                trusted_proxies 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.19
        }
}

www.example.com {
     import example_backend
}

The list of IPs must be updated from https://www.cloudflare.com/ips/ perdiodically. It might be prudent to setup an auto-update script to write out a seperate configuration file just for cloudflare's reverse proxy template and import that file instead.