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
</IfModule>
<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
</FilesMatch>
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>
<FilesMatch "\.(htm|html|php)$">
FileETag None
Header set Cache-Control "max-age=86400, public, must-revalidate"
</FilesMatch>
<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"
</FilesMatch>
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"
</FilesMatch>
I'm a Front-End Engineer at Yahoo! working on the Mail and Messenger teams. I blog about web design and development topics including accessibility, usability, performance, and developing HTML / CSS / JavaScript applications on Appcelerator Titanium and Adobe AIR.
If you're a web developer, you might enjoy Jelo, my JavaScript library.
A few panoramic shots I took at SDCC 2010. #geek http://bit.ly/bwX6GB
JS version of Regex prime number checker:
function isPrime(n) {
return Array(n + 1).join("1")
.search(/^1?$|^(11+?)\1+$/) == -1;
}
Погрузился в пучину EcmaScript5, местами увлекательно, местами нудно =)
Modernizr http://ow.ly/18njQ1
A Collection of 20 HTML5 Video Players - a round-up of JavaScript and html5 alternatives to Flash-based media player... http://ow.ly/18njQ2
jQuery TOOLS - The missing UI library for the Web http://ow.ly/18njQ3
Contactable - A jQuery Plugin | the odin http://ow.ly/18njQ4
Giants vs Dodgers, sweet seats. http://twitpic.com/2ag9pa
@snookca That'll be fixed next week. I promise.
@snookca I was tryna not name names ;) But really that was just par for the course today, pretty hectic day. As I'm sure you know.
Who breaks major stuff after 4pm on Friday? On the last day of the sprint, no less. Tsk. (wasn't me)
Awesome live git tracker for teams: http://www.utsup.com/
RT @DerrenBrown: Blog post: Camera Software Lets You See Into the Past http://bit.ly/9kjVg5
10 invites to the new version of Digg: http://bit.ly/dqM8EV
Threaded vs Evented Servers, great look at the whats and whys. http://bit.ly/bDUEjn #geek
Nav, Context menus, "app-style" toolbars in sample chapter http://bit.ly/csTRY8 of new YUI book http://bit.ly/cJINoV
Add a side-mounted End Call button to your iPhone 4: http://bit.ly/cGxPBD #funny #geekAll original work on this site is covered by a Creative Commons Attribution 3.0 license unless otherwise specified.
You may share or use any code or images from this site in any manner, for free, so long as reasonable effort has been made to give credit where due.
The views expressed in the posts and comments on this blog do not necessarily reflect the views of Yahoo!