Shane Chism

Set Cache Expiration in Apache htaccess


Description


In the quest to cut down page load times, caching of files is an important consideration. By setting distant expiration dates for your files, you can ensure that users hold onto your files for a long time.

Warning: By setting distant cache expirations, this will prevent users from re-downloading your file until it expires. This means that, should you upload a new version of a file and not change its name, a user won't download the new version until their current version expires.

This can be avoided by changing the name of new files, or by appending a query string (i.e my_image.png becomes my_image.png?var=some_arbitrary_value).

Usage


There are two ways you'll need to configure this code. Take a look at the full code:
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|js|css)$">
	Header set Cache-Control "max-age=604800, public, must-revalidate"
</FilesMatch>

The types of cached files are controlled by this regular expression:
"\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|js|css)$"

In the above example, we're caching the following files: ico, pdf, flv, jpg, jpeg, png, gif, swf, js, and css. You can modify this expression to suit your own needs.

Next, we specify how long these files should stay cached before their re-downloaded:
Header set Cache-Control "max-age=604800, public, must-revalidate"
The important number here is 604800. This number should be replaced by the number of seconds before the file expires. In our case it's one week:
7 Days * 24 Hours * 60 Minutes * 60 Seconds = 604800

Google recommends caching for at least one week.

Code

.htaccess.new
View Plain   Download Code
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|js|css)$">
	Header set Cache-Control "max-age=604800, public, must-revalidate"
</FilesMatch>


 
Apache
OCTOBER 18 2011
Download
30 DOWNLOADS