&. |

A software developer’s musings on software development

A simple solution to cached CSS files

Warning: I wrote this blog in 2008. That is a long time ago, especially on the internet. My opinions may have changed since then. Technological progress may have made this information completely obsolete. Proceed with caution.

I’ve come up with a very simple solution to the problem of browser-cached CSS files. What I mean by this is: when you update the CSS which manages your website’s presentation, it will take a while before some visitors actually see those changes. The reason, of course, is that browsers (this is at least true of IE and Firefox) will cache CSS files pretty aggressively, without checking very often to see if they have been updated. Usually refreshing the page will solve this, but most visitors aren’t going to care enough to do this. Meanwhile, your site will look pretty broken to them (especially if you’ve done something like styled a list so that it looks like a horizontal toolbar instead of a bulleted list, for example).

So here’s the very simple solution. Add the following rule to your root .htaccess file:

RewriteRule ^(.*).[d].css$ $1.css [L]

I’m assuming that you have a common include file or template or something which prints things like the page header. If so, whenever you update your CSS file (say, style.css), you update the link tag in your header to use style.0.css. This will look to the browser like it is a different file from style.css, so it will download it again. But Apache is really just loading the same CSS file through the magic of URL rewriting—you’re just ensuring that the user picks up your recent changes. You can repeat the process the next time you tweak your CSS, just change the header to style.1.css and so on.