Caching static HTML with Cloudflare

By default, Cloudflare does not cache static HTML. It's nice when you're constantly pushing updates because the changes are immediately shown. But it does mean that you still have that short delay whilst Cloudflare gets the latest version of your page.

If you have a completely static site, like I do with this blog, you can add a page rule to cache everything and it will speed up your page load time.

Cloudflare has a guide on how to cache the static HTML if you have a specific folder or .html extension. For simplicity's sake, I ended up just making a Page Rule for* with the setting Cache Level: Cache Everything. This is kind of the brute force method, but it works.

The only problem that's left is everytime you do push an update, you have to clear the cache in Cloudflare. An easy way I've been doing that is with the Cloudflare API. I added a function into my .bashrc which curls off to their API to clear the cache. You could also add it into some sort of CI or git hook if that's convenient.

cloudflare-cache () {
    curl -X POST "<website zone>/purge_cache" \
     -H "X-Auth-Email: <email>" \
     -H "X-Auth-Key: <auth key>" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}'

You can find the parameters you need on the website page in Cloudflare.