.htaccess: Cache Control, how can I handle Website Updates?
I just searched the web but could not find a good answer to this:
The Google page speed extension for FF told me to cache files on my website (PHP). Therefore I updated my .htaccess
(in my beta-area of the website) in order to cache certain types of files:
ExpiresActive On
ExpiresDefault A0
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
While coding in the beta area, I noticed that due to the cache control settings, I need to press F5 to get the lastest .css file for example. That's not bad for me... however what about the user开发者_高级运维s?
So can I tell the browser to re-download all files (only) when I update my site (or the file expires) and use the cache if not?
It would be perfect if I could tell the browser: "Hey, all files before Update-time are old, please re-download them - however files after Update-time are ok, use the cache."
Here's a simple approach I sometimes use, which doesn't require any complication configuration.
Whenever you modify a css or javascript file, simple add a dummy parameter to the markup. I typically use the current date and/or time. For example:
<link type="text/css" rel="stylesheet" href="site.css?120911" />
This forces the browser to download a new copy of the file when you need to update it, while still allowing you to maintain consistent file names behind the scenes.
For performances reasons, you have indicated to the browser that it should cache a file, without requesting it from the server before a long time.
That's what the browser is doing : using the file from the cache, not asking anything from the server -- and this is the right behavior.
When you modify a file, to force browsers to re-request it, and get the new version, the only solution you have is to change its URL.
Typically, this is done by integrating a version number in the file's names :
http://www.yoursite.com/my-file-123.css
And, when a the file is updated :
http://www.yoursite.com/my-file-124.css
As the URL has changed, the browser doesn't have the file in its cache, and requests the new version from the server.
Of course, doing this by hand is quite not easy, and is error-prone...
So, generally (provided you have a build-script, that extracts the sources of your website from source-control, and packages them for production), you'll integrate this process in your site's building script.
精彩评论