Using YSlow, Apache and Passenger to make your site Faster – Stage 1 Expiries

Stage 1. Adding an Expires header to Static Pages with Apache and Phusion Passenger

Yslow is a great tool to check how your site compares on several factors relating to speed.

I ran a check on Dynamic50.com and I got 76%. I want 100%, so lets get started!

Firstly YSlow recommends I add an expires header to my website. Now since this is a static site, I can afford to set the expires header pretty far in the future. First step is to log into your server, mine is slicehost running apache2 and phusion passenger.

Make sure you have all the extras apache has to offer:

sudo apt-get install apache2-mpm-prefork apache2-utils libexpat1 ssl-cert apache2-prefork-dev

Now lets make sure the required module is enabled:

sudo a2enmod expires

Now I am going to set the expires header for all assets on this site. So I go to the virtualhost configuration for dynamic50.com which is in "/etc/apache2/sites-enabled" and add the following lines:

<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
        ExpiresActive On
        ExpiresDefault "access plus 1 year"
</filesMatch>

Now what happens if the image changes? Well the best way to solve this is to include a rewrite rule in the virtualhost to amend the timestamp of the file on to the end of the filename, meaning when a new file of the same name is uploaded, it will have a new timestamp and therefore appear as a completely new file and be loaded.

Firstly make sure you have rewrite on:

sudo a2enmod rewrite

Now add the following rewrite rule to your virtualhost:

RewriteEngine On
RewriteRule (.*)-cb\d+\.(.*)$ $1.$2 [L]

And restart apache2:

sudo apachectl graceful

Hey presto its done!
Now I run YSlow again, and I have an A for Expires headers. Nice

3 Comments

RSS feed for comments on this post. TrackBack URL

  1. Reelix — February 25, 2010

    Any way to do this using normal PHP on the page? No Apache access to my host (shared hosting)…

  2. nogeek — February 25, 2010

    Yes you could probably add it to your .htaccess file in the root directory of your wordpress install. Give it a go and let me know if it works!

  3. Kailas — March 26, 2011

    I’m confused… if we do this mod_rewrite:

    RewriteEngine On
    RewriteRule (.*)-cb\d+\.(.*)$ $1.$2 [L]

    isn’t this going to put a new timestamp on every single component leaving the box? and, as such, will it not cause the browser to download a new copy for every resource, and there by, defeat the whole purpose of the Far Future Expires directive?

Leave a comment

Preview: