Enable Browser Caching of Static Assets

If you’ve used the Page Speed tool in Firefox to test your page load times, one of the things you probably received a warning about was something like Enable browser caching of static assets saying “FAILED (No max-age or expires)’.
What this means is you haven’t set any information on your site to tell browsers visiting the site how long to keep the static files like header graphics, icons, and other things that rarely change on your pages. For most visitors this won’t matter because even at sites like Yahoo, something like 40-60% of visitors haven’t cached the content. For the half that have, you save them a ton of time by pulling files from the local machine and not from your server. For the longest time, I couldn’t figure out how to set caching on specific assets, but I’m sharing it here in hopes it will save you time in the future.
The easiest way to set up caching rules for browsers is using the .htaccess file in your website’s root directory. You should use something like the following:
ExpiresActive On
ExpiresDefault “access plus 2 hours”
ExpiresByType image/gif “access plus 30 days”
ExpiresByType image/png “access plus 30 days”
ExpiresByType image/jpg “access plus 30 days”
ExpiresByType text/css “access plus 30 days”
ExpiresByType text/html “access plus 60 seconds”
Basically the first directive turns on the caching rules. The second directive says the default time to cache things is 2 hours from the time of access. Each of the image directives tells the browser to cache image of those types for the original time of access plus 30 days. You can replace days with hours, years, months, minutes, or seconds or can further refine the time to something like ExpiresByType image/jpg “access plus 2 months 30 days 5 hours 3 minutes 2 seconds”. Note that you may want to set the time for text/html to be very short if you have active comments so as to avoid people not seeing the updates.
Images are fairly safe places to cash for long periods of time, but if you modify your CSS, you will want to either change the name of the file when you republish or set the cache for your CSS file to a much shorter timeframe.