Optimize browser caching (expires headers)

Expires headers are very important for browser and if set correctly can reduce your websites loading times by a lot. If big files like your scripts, css or a background image don't change very often, setting big expiry times can help your users browsers to keep those file longer in their cache. This will reduce the loading time of the page(s) but also reduce the bandwidth used.

Apache expires directive (put it in your apche .conf file or into your htaccess):


ExpiresActive On
ExpiresDefault "access plus 1 day"
ExpiresByType image/jpg "access plus 1 month"
# (...) set the expires by type for the files your hosting
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "public"
</filesMatch>

Nginx expires directive (put this into your nginx .conf file):


location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires max;
    add_header Cache-Control "public";
}

In your php scripts use a line of code, like this one:


<?php
$offset = 60*60*24*1;
header('Pragma: public');
header('Cache-Control: private', false);
header('Expires: '.gmdate('D, d M Y H:i:s', time()+$offset).' GMT');

So now you have set expiry times that are far far into the future, but what if you have to do changes on one of these pages and want to ensure that all your users get this new files during their next visit and not in a far far future when the file expires in their browser cache. The answer to this problem is versioning. Add a version number to all your files. So if the users browser has cached mycss-0.0.1.css and you publish mycss-0.0.2.css the browser will notice that it's a different file he hasn't in his cache and will download it.