Getting Around Browser Cache with .htaccess
Posted by Steve Lounsbury on January 9th, 2009
It’s pretty common to tweak your website assets from time to time. This may be an update to a stylesheet, some javascript, a logo or any other file. When doing this, you may notice that you don’t see the changes right away. You might have to refresh the page a few times or clear your browser cache in order to get the new version of the file. There are a few reasons this can happen:
1. When your browser requests a file, Apache may report that the file hasn’t changed. You can see this with a tool like firebug, any files that come back with a “304 Not Modified” header will not be re-downloaded by your browser.

2. When you first requested the file sometime in the past, Apache may have sent an expires header with the file. This means that until a specified date, your browser will never re-download the file. Unlike the #1 above, it doesn’t even ask Apache if it should re-download the file.
Note: I’m sure I missed a few ways a file can find it’s way into the cache, but that’s not the point of this post.
All this caching is great for the performance of your website, but it sucks when you actually want your users to download the new version of the file. Putting up “our site has changed, please clear your browser cache” is obviously out of the question. So, what can we do?
When your browser encounters a file that it hasn’t seen before it will always go ask Apache for the file. So, one option is to add a version number to the filename and update your source to point at the new file. This works, but adds a maintenance overhead because you have to make sure you maintain the version number of the file and deploy it with the proper filename. So, style.css could become style-20090109.css.
The problem with the above is that you have to maintain the file version in two places, once in your source html and again when you update the css file. We can get around this using htaccess by pointing all reguests to style*.css to style.css. So, when a request is made for style-20090109.css you get the updated contents of style.css and since the filename is unique you get around the cache issues. Yes, you still have to maintain the reference to the stylesheet in your html source, but you don’t have to worry about how to name the file. Anyway, here’s how you go about doing this.
Create a .htaccess file in the directory where your style.css file lives. In it put the following:
RewriteEngine On
RewriteRule ^style(.*).css$ style.css [QSA,L]
Now, when you request style-20090109.css or style-monkey.css you’ll always get the contents of style.css. There are other solutions, but I find that this works best for us. Hope someone will find it useful.








