Setting Cache Control Headers to Speed Up Your Site
Well, I took a quick look at my Page Speed results today, and it looks like Google is angry at me for my inability to leverage browser caching. Essentially, I’m reaching out to the server for every image on my site, even if the user has loaded it already. Seems like a ton of extra unnecessary work eh?
Well, htaccess to the rescue! I added the following to my .htaccess file, which sped up my site considerably (and also upped my Page Speed score). I opted to set my headers to a long time for both images, css, and js for now, since I don’t really update the look of my site that often. When I do decide to, I’ll most likely rename my js and css files, and removed the old ones.
htaccess
# Setting Cache Control Headers # 480 weeks <filesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$"> Header set Cache-Control "max-age=290304000, public" </filesMatch> # 2 DAYS <filesMatch ".(xml|txt)$"> Header set Cache-Control "max-age=172800, public, must-revalidate" </filesMatch> # 2 HOURS <filesMatch ".(html|htm)$"> Header set Cache-Control "max-age=7200, must-revalidate" </filesMatch>
Anyone out there have any suggestions on ways to set cache control? This was my first attempt at it, and I’d love some feedback!
Edits
While this is a decent way of setting this up out of the box, I’ve switched to using the W3 Total Cache plugin for browser cache control, as well as many other speed improvements.
Comments (6)
Leave a Reply
Also remember when you update your files you don’t need to change the file names to bust the cache just change how they are loaded.
Link to commentFor cache-busting what I’ve done is include a timestamp/build number/svn(or mercurial or git) revision id in the file name so you end up with something like main.20120202.css, that is added by the build process, then in my html files, I just use something like maven or ant filtering to add the unique identifier to the link and script tags, that way it guarantees you that when the files change, the references will be updated as needed. Obviously that requires that you’re using a build system of some sort to maintain the code. There are probably other, better ways to do it, but its worked for my needs.
Link to commentI definitely like that Idea. Know of any good php implementations?
Link to commentI tried this code and had no change in my pagespeed leverage browser caching results. Any ideas?
Link to commentWhat site is it Grady? http://www.simplythebestcleaning.biz/?? I ran a page speed test on it, and it looks like the cache control headers are not setup, or are set to a short time. Can you send me a screenshot of your results? What did you put in your htaccess file?
Link to commentJust an update, this site was on a shared host which didn’t allow the php needed for using cache control. The site is now on my own server and everything is groovy. Now getting a 94 on google pagespeed 🙂
Link to comment