Site optimisation with .htaccess

19th May 2009

With the launch of this new site I've been spending quite a bit of time looking at templating some of the things that I do when developing to save me time and maximise my output (check me out I'm like a slogan on a cheap 80's office calendar).

Anyone who develops using Firefox will probably already have the Web developer toolbar and the YSlow plugin. YSlow does a great job at assessing the performance of pages on your site and gives you a grade (A-F) of how err, performant (yeah I know) the page is. It breaks down the overall performance into different sections and grades you on each, pointing out where improvements can be made.

I usually get good grades for most of the sections with the exception of these ones:

  • Use a Content Delivery Network (CDN)
  • Add Expires headers
  • Compress components with gzip
  • Configure entity tags (ETags)
  • Use cookie-free domains

First off, some of these I don't want to do anything about for the time being. I have no intention of using a Content Delivery Network (This is a great article for anyone interested in setting up Amazon S3) and I'm not planning on using a cookie-free domain, but the others I can address quite easily.

So after a bit of hunting around, progging and poking I present to you an extract of my .htaccess file, which adds expires headers, compresses the compressable and configures entity tags (well, turns them off).

If you host your sites on an IIS server, I'm afraid this will be of litte use to you. Sorry.


<ifmodule mod_headers.c>


# Turn off ETags
Header unset ETag
FileETag None

<ifmodule mod_expires.c>
# Turn on Expires and set default to 0
ExpiresActive On
ExpiresDefault A0

# turn off last modified for these things.
<FilesMatch "\\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css)$">
Header unset Last-Modified
</FilesMatch>

# Set these things to cache for 1 year
<FilesMatch "\.(flv|ico|pdf|mp3|wav)$">
ExpiresDefault A29030400
Header append Cache-Control "public"
</FilesMatch>

# Set these things to cache for 1 week
<FilesMatch "\.(gif|jpg|jpeg|png|swf|js|css)$">
ExpiresDefault A604800
Header append Cache-Control "public"
</FilesMatch>

# Set these things to cache for 2 hours
<FilesMatch "\.(xml|txt|html)$">
ExpiresDefault A7200
Header append Cache-Control "proxy-revalidate"
</FilesMatch>

# No caching for dynamic stuff please
<FilesMatch "\.(php)$">
ExpiresActive Off
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>

# try to catch any stragglers
ExpiresByType image/* "access plus 1 month"
</ifmodule>
</ifmodule>

There you go.

Tagged with: Apache, .htaccess, Optimisation, YSlowback to top ^