Web Standards Group

Resources

Speed Up Sites with htaccess Caching

Posted: Wednesday 07 March, 2007
By: Caleb Duke

Implementing this method will save you incredible amounts of bandwidth and drastically speed up your site for your site visitors.

Basically most images, css, javascript, and other files can be optimized for faster download by telling your site visitors to cache them for a certain period of time. The default behaviour is to check the last-modified and/or the Etag headers of the file EVERY time it is requested.

So a user goes to /home/index.html, and the browser caches all the images and files. Then the user leaves the site and comes back later, and the browser has to send If-Modified-Since conditional GET requests for every cached item, basically to see if the file has been changed and if they should update their cache.

When you implement the caching method described in this article, you can specify that certain files or filetypes be cached for a specific amount of time. These files are then cached by your site visitors and they do not send the If-Modified-Since until the set cache time has completed.


The first solution is the Apache Module mod_expires 1.3|2.0|2.2

ExpiresActive On 
ExpiresDefault A300 
ExpiresByType image/x-icon A2592000 
ExpiresByType application/x-javascript A2592000 
ExpiresByType text/css A2592000 
ExpiresByType image/gif A604800 
ExpiresByType image/png A604800 
ExpiresByType image/jpeg A604800 
ExpiresByType text/plain A604800 
ExpiresByType application/x-shockwave-flash A604800 
ExpiresByType video/x-flv A604800 
ExpiresByType application/pdf A604800 
ExpiresByType text/html A300 
 

The second solution is mod_headers 1.3|2.0|2.2

# 1 YEAR 
 
Header set Cache-Control "max-age=29030400, public" 
# 1 WEEK 
Header set Cache-Control "max-age=60800, public" 
# 3 HOUR 
Header set Cache-Control "max-age=10800, public"
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
 
 

The third solution is a hybrid of both mod_expires and mod_headers

# Turn on Expires and set default to 0 
ExpiresActive On 
ExpiresDefault A0 
# Set up caching on media files for 1 year (forever?) 
ExpiresDefault A29030400
Header append Cache-Control "public"
# Set up caching on media files for 1 week
ExpiresDefault A604800
Header append Cache-Control "public, proxy-revalidate"
# Set up 2 Hour caching on commonly updated files
ExpiresDefault A7200
Header append Cache-Control "private, proxy-revalidate, must-revalidate"
# Force no caching for dynamic files
ExpiresDefault A0
Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
 

NOTE: Using FilesMatch and Files in htaccess

Here is what the Headers look like when downloading a JPEG image, with this caching scheme implemented, and without.

JPEG WITHOUT CACHING

Last-Modified: Wed, 22 Feb 2006 12:16:56 GMT 
ETag