Last Updated: February 25, 2016
· thomaspuppe

Force Cache-Refresh at CloudFront with virtual versioning

We recently started using Amazon CloudFront for hosting/caching assets of big client's websites.

Combined with far-future cache headers (which you really should use!), you can drop the traffic of your servers siginificantly.

But there is a downside with Cloudfront. If you want to push new contents of a file out to the world, you either need to rename it (and all references to it), or you have to start cache invalidation in the Cloudfront panel (which does cost extra money?).

As a solution, I introduced virtual versioning of folder names by adding a one-line rewrite rule in our server's .htaccess file.

When linking to files, we use "/assets/version_2013-02-14/backgroundimages/1.jpg" as URL (with anything behind "version_"), and files are always at "/assets/backgroundimages/1.jpg".

<IfModule mod_rewrite.c>
    RewriteRule ^assets/version_(.+)/(.*) /assets/$2 [L]

When you want to force CloudFront to fetch the new version of a file, you simply change the string behind "version_". Cloudfront does not know this file, fetches it from your server (where the only existing file is pulled freshly) and serves it as long as you do not change the versioning part of the URL.

Using Parameters like "1.jpg?v=2013-02-14" is not a good idea, since this has a worse caching rate with browsers and proxies.

(I see there are many cases where you can simply rename the file itself. But in our case this was not a prefered solution.)

Say Thanks