Implementing cache-control with Apache 2
Written by Robin Fisher in 263 words
15
Apr
With Google’s decision to include page speed in the factors it uses to decide ranking, it’s more important than ever to increase the speed with which your page loads. The Google Page Speed plugin in for Firebug is a great way to identify what is slowing down your page and where improvements can be made.
One of the areas that I could improve on captured sparks was to explicitly set how I wanted my content to be cached. This site is running on Apache 2 so these instructions are for that versions:
cd /etc/apache2/mods-enabled
Check to see if mod-headers and mod-expires are enabled. If not:
cd /etc/apache2/mods-available sudo a2enmod headers sudo a2enmod expires sudo /etc/init.d/apache2 force-reload
If these modules are not compiled, you will need to do so.
Although I have access to my httpd.conf file, I’ve implemented cache-control in my sites .htaccess file.
<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|swf)$"> Header set Cache-Control "max-age=2592000" </FilesMatch>
This sets the expiry of images and flash to 1 month from the request date as these are unlikely to change particularly frequently.
<FilesMatch "\.(js|pdf)$"> Header set Cache-Control "max-age=604800" </FilesMatch>
This sets the expiry of javascript and pdfs to one week from the request date.
<FilesMatch "\.(html|htm|css|txt)$"> Header set Cache-Control "max-age=43200" </FilesMatch>
Finally, this sets HTML, stylesheets and text files to expire 1 day from the request. As I am making changes to my site every couple of days at the moment (refining is the word), I need a short expiry time.

Inspecting an image with Firebug, you can see that they will now expire 1 month from today at which point the browser will request the file from the server again.