Caching a static website on Cloudflare

by on

Cloudflare is a cloud-based solution to protect your website against attacks. One way to mitigate (DDoS) attacks is providing a geographically distributed network of POPs with a lot of bandwidth. And that’s exactly what they did: Cloudflare maintains a content delivery network with 30 data centers around the world. Even if you have no reason to suspect being attacked any time soon, the speed improvement is well worth it.

Setting up their service is pretty straightforward. Move your domain to their nameservers and select the subdomains that have to be protected. Important to note: Using the CDN routes all traffic to your website through the Cloudflare network. This means that you’re basically allowing them to do a man-in-the-middle attack on your visitors. This article is aimed at static websites, so it doesn’t really matter, but it’s something to keep in mind.

Caching

By default, Cloudflare caches resources that are supposed to be static on most websites. This includes images, stylesheets and javascripts. Your server is contacted for every pageview, but most assets are offloaded to their edge servers. This is great for a dynamic website, as we want to make sure that visitors see their personalized version of the website. Static websites, however, may benefit from being cached completely.

First things first. In the Cloudflare site settings page, we see three cache levels:

The cache level setting only applies to those resources that Cloudflare decided to cache. I usually set this to Agressive for static websites, as it allows me to change a hash in the query string to invalidate the cache when updating a page.

A second interesting setting is the minimum expire TTL, this allows you to overwrite the expire time in the cache-control header. When setting up a static website, I expect these headers to be set correctly on the origin server, but this may come in handy when you have little control.

Cache Everything

The setting we’re looking for is hidden deeper in the Cloudflare admin panel. In order to make their CDN cache everything, you need to create a page rule. Page rules define custom settings for a given subset of your website. Click the gear icon next to your website and select Page Rules. Between the rule settings an item named Custom caching appears. Set this to Cache everything to, well, cache everything. This only applies to the URL pattern specified for the page rule.

Two other interesting settings:

Try it out! Depending on the number of visitors, caching everything may save quite a lot of bandwidth! If you have only a few visitors per month, you may not even see it, especially when they are geographically distributed. It looks like Cloudflare does not share resources between edge servers. If a resource is not available in the POP closest to your visitor, it contacts the your server.