What's the Best Way to Handle Caching with Cloudflare?
Asked by
fricative
I'm currently using Cloudflare for my website, but I've noticed that its caching often messes with the CSS and images. I suspect my configuration isn't quite right since it defaults to recommended optimizations that might not suit my needs. I want to improve the caching process to take full advantage of it without losing content. I'm trying to decide between two caching strategies: one where content is cached for a set period, meaning clients will have to wait until it expires to see new content, and the other where everything is cached for a year, requiring version updates whenever changes are made to notify the browser about cache invalidation. My question is whether I should implement these strategies in my backend, within Cloudflare, or possibly both for the best results.
Answers
One strategy is to implement cache busting based on the file modification time (`filemtime`). This way, you can ensure that any changes will trigger a refresh without too much hassle.
Reply to this answer
Honestly, I just ignore the issues! But if you're looking for concrete strategies, my caching varies depending on the resource type. I use unpkg for CDN resources with versioned URLs, ensuring those donโt change unexpectedly. For same-origin stuff, I rely on validation techniques like etags. It minimizes server hits while keeping load times quick.
Reply to this answer
The key is to understand the difference between browser caching and edge caching. For CSS and JS files, you should set the cache to one year, and whenever you update those files, just rename them. For your HTML pages, go shorter with a five-minute cache time and set the edge cache to a year. Once you've renamed your CSS or JS files, purge the cache for your pages to make sure they're using the latest files. You might also want to think about putting images and CSS/JS on a different domain to make purging easier without affecting all your assets.
Reply to this answer
From my experience with Cloudflare, we handle caching by: 1. Renaming generated files like CSS/JS with every build. 2. Adding URL variables for non-generated files that may change, like images. 3. Occasionally purging the entire site's cache in Cloudflare to prevent serving outdated files.
Reply to this answer
Whenever you make changes, make sure to flush the cache. Keep in mind, though, browsers might still hold onto some cached files. Itโs helpful to use versioning techniques like appending `?v=x` to file URLs when changes occur.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions