Caching php files on Cloudflare

Oh dear, I’ve definitely broken my New Year’s resolution now – it’s been 16 days since my last confession… I mean blog post!

I’ve spoken before about how I use Cloudflare to improve both security and performance.  In short, they have an ever increasing number of edge nodes, which they cache content at and then return results directly, in the same way that a CDN would for static files.  By having this distributed network of nodes, they can return results super quick, and reduce the amount of bandwidth my origin server is using to fulfill all the requests (as the ones Cloudflare return from cache never even hit my origin server!).

On digging into my stats a little deeper, it became clear that Cloudflare wasn’t caching everything, and it didn’t take long to figure out why.  They only cache file extensions they consider to be static content, such as stylesheets (.css), javsacript (.js), images and documents.

For me, I use PHP as the language for my server-side code, which has the file extension .php – not in their list, as it’s not static.  However, in a lot of cases, the content is relatively static on my site, and just has things like the copyright notice which is dynamic, but as this only changes once a year, it’s near enough static.

In order to fix this, I can use a neat Cloudflare feature called “Page Rules”.

Go to the “Page Rules” section and then click the “Add Page Rule” button.  You get presented with a dialog like the one below…

As you can see, I’ve put in a URL pattern that matches all of my PHP files, and then chosen the setting “Cache Level” equals “Standard”.  This means that these pages should now be cached correctly, in the standard cache mode.

There are loads of settings that you can choose from here, so this is a really powerful feature to customise exactly the way that your site works, and add exceptions for individual URLs, or groups of URLs.

At the time of writing, you get 3 Page Rules for free, but you can buy additional ones for a monthly fee.

Leave a Reply

Your email address will not be published. Required fields are marked *