Configuring content caching for speed optimisation

By default, Apache does not apply browser caching headers to any content it serves to users. Although this is desirable if you are testing or developing a website, the reality is that for the majority of the content you serve, it does not change frequently. This is especially the case for images, javascript and CSS files on a production website. Enabling caching on the browser side will mean that users make far fewer subsequent requests when navigating to additional pages, as they no longer have to make a repeated request for a resource already downloaded. End result: faster page loads and lower server and bandwidth requirements.

How to

Create a file in the Apache configuration directory and include the below contents:

# cd /etc/httpd/conf.d/ # vi cache.conf

Add the following contents to the file.

<IfModule mod_headers.c> 
  <FilesMatch ".(flv|swf|gif|jpg|jpeg|png|ico|js|css|pdf|txt)$"> 
  Header set Cache-Control "max-age=604800" 

Note: This is configured to serve all the listed file types with an expiry of one week (the minimum recommended value). You can tweak the age value and also split the file types out into different sections if you wish to be more granular. We also choose not to cache any HTML or PHP files due to the dynamic nature.

Once you have saved the contents of the file, confirm the Apache configuration then restart the service.

# apachectl -t 
 Syntax OK 
 # service httpd restart 
 Stopping httpd: [ OK ] 
 Starting httpd: [ OK ]

Don’t forget to check your site for any issues that this may raise (although unlikely) and also test the speed benefit achieved from this change.

Cache busting

Should you need to force any resource to be updated for all users, regardless of the caching settings, the best way to do this is to create a resource with a new name and reference that. If you wish to force an update to occur only for your local browser then you can simply complete a “hard refresh” within your browser.

Leave a Reply

Your email address will not be published. Required fields are marked *