Speeding site load times with htaccess

Create an “.htaccess” file in the folder you want to be cached and add the following to it.

# Cache files for a week.
<IfModule mod_headers.c>
  <IfModule mod_expires.c>
    <FilesMatch ".(jpg|jpeg|png|gif|swf|css|js)$">
      Header set Cache-Control "max-age=604800, public"

This will have the effect of caching your site for a week. The number 604800 refers to the number of seconds in a week you should also see the file types mentioned in the line above. Change them as you see fit.

You will need mod_headers and mod_expires enabled in your apache htpd.conf for this to work, but with the ifmodule statements in there there should be no problem if they aren’t installed. If it wasn’t for the two ifmodule statements your site would be dumped to a 500 server error if it couldn’t find them.

To check the expiration times I find the easiest way is to load the page in Firefox, right click somewhere and hit “View page info” then go to the media tab. You will see date and time for the expected expiry of the image files on your site.

David Coveney

David Coveney

Dave has been working in software development since 1988, starting with payroll development and then ERP consultancy for large corporates. He is a keen traveller, photographer and motorsport enthusiast, but now puts family first as he’s massively in love with his two little boys. Dave is still an early adopter. He was connected to the internet from his bedroom, way back in the eighties, had a personal website by 1994, was into the connected house in the late '90s, a smartphone by 2002, and a was the first in the office with a fitness tracker.

Leave a Reply

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