start blog post

.htaccess: Cache Rules Everything Around Me

Properly configuring the cacheability of your webpages and other components can greatly improve the performance of your site for returning visitors. The longer a component is cached, the less often that same visitor has to redownload the component, saving you bandwidth and your visitors time. There are many ways to set HTTP headers for caching.

    // Example 1: cache via PHP headers
    if (!headers_sent()) {
        $offset = 60 * 60 * 24 * 7; // how long to cache the file, in seconds
        clearstatcache();           // important to call this before using filemtime()
        $lastmod = gmdate('D, d M Y H:i:s', filemtime($f)) . " GMT";
        $expires = gmdate('D, d M Y H:i:s', time() + $offset) . " GMT";
        header("Cache-Control: private, pre-check=$offset, max-age=$offset, must-revalidate");
        header("Content-Type: text/html; charset=utf-8");
        header("Last-Modified: $lastmod");
        header("Expires: $expires");

Headers must be sent before any text is sent to the browser (even blank lines). If you try to set the headers after outputting anything at all, you'll raise a warning and the header will not be set.

Example 1 tells our viistors to cache our page for one week. You could calculate that value yourself (60 seconds * 60 minutes * 24 hours * 7 days = 604800) but leaving it as an expression makes it easier to adjust later if need be.

    # Example 2: using .htaccess with mod_expires
    <IfModule mod_expires.c>
        ExpiresActive on
        # 60 seconds * 60 minutes * 24 hours * 7 days
        ExpiresDefault A604800
        # 60 seconds * 60 minutes * 24 hours
        ExpiresByType text/html A86400
    <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|js|css)$">
        # configure ETag
        FileETag -INode MTime Size
        # max-age set to one week as above
        Header set Cache-Control "max-age=604800, public, must-revalidate"
        # if you use ETags, you should unset Last-Modified
        Header unset Last-Modified

The benefit of using .htaccess to set your content headers is that you don't need to worry about accidentally trying to set headers after content has already been sent to the browser — .htaccess always hits before your page.

The FilesMatch directive lets you fine tune HTTP headers for certain file types, based on the regular expression inside the FilesMatch tag. Example 2 applies the rules to images, Adobe PDF documents, embeddable videos, JavaScript files, and CSS stylesheets.

    # Example 3: .htaccess when mod_expires is NOT available
    <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3)$">
        FileETag -INode MTime Size
        Header unset Last-Modified
        Header set Cache-Control "max-age=86400, public, must-revalidate"
        Header set Expires "Thu, 31 Dec 2010 20:00:00 GMT"
    <FilesMatch "\.(htm|html|php)$">
        FileETag None
        Header set Cache-Control "max-age=86400, public, must-revalidate"
    <FilesMatch "\.(js|css)$">
        FileETag None
        Header set Cache-Control "max-age=604800, public, must-revalidate"
        Header set Expires "Thu, 31 Dec 2010 20:00:00 GMT"

The Net tab of Firebug will show you exactly what headers your web server sends for every single file. If you tried Example 2 but your Expires headers are missing or incorrect, your web server may not include the mod_expires module. The good news is that Example 3 should still work for your server. The less good news is that I think your Expires headers must be set to an explicit date and time, rather than a time relative to when the visitor last accessed the component. To avoid having to change our .htaccess file every week to add more time, Example 3 sets it to a date and time far in the future, and relies on the Cache-Control header to handle the rest.

What if you don't want some files to cache at all? Dynamic ages that can change each time they are accessed should not be cached, and Example 4 shows how to

    <FilesMatch "\.(php|cgi|pl|htm)$">
        ExpiresDefault A0
        Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
        Header set Pragma "no-cache"

var tags = [, , ];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

most viewed this week

least viewed this week