I’m trying to learn how to use .htaccess to manipulate my headers and, in Google’s words, “leverage browser caching” to improve pageload times. The code I’ve experimented with is this:
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
<FilesMatch "\.(js|css)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
<FilesMatch "\.(html|php)$">
Header set Cache-Control "max-age=14400, public"
</FilesMatch>
For some reason, this is causing the entire website to throw a 500 error. In case it makes any difference, I’ve inserted this code very early in the .htaccess file, before some authentication logic that requires a password for certain subdomains and a long list of 301 RewriteEngine redirects, because this website was recently reorganized and a lot of URLs have changed.
Do you know why this is causing an error? I more or less copied the code from a blog and edited it to suit my needs. The 500 error also doesn’t crop up immediately after I update the .htaccess file, which to me implies that the error is starting AFTER the Apache server’s default four-hour cache expiry header lapses.
EDIT 10-17-2012:
Having tried adding and removing this code a couple of times now, I’ve confirmed that the headers DO WORK, albeit briefly. Using FireBug with PageSpeed, I can see that the max-age settings are being correctly applied to the files. Then after a while, as I’ve mentioned before, the website CHANGES to all 500, all the time.
Another thing worthy of note: I’m actually trying to test the new headers on a password protected test subdomain before rolling it out to the main site. As far as I can tell it looks like for some reason, after updating the .htaccess on the SUBDOMAIN (which even runs out of its own folder, separate from /public_html/), the MAIN (www) site breaks.
It’s possible that I’m doing something wrong, or accidentally uploading to the main site when I think I’m updating the test subdomain, but I’m becoming hesitant to risk more downtime on the main site over this.
It’s possible my 500 errors have nothing to do with the caching code, but with my site’s Control Panel. Apparently, just accidentally clicking on its built-in .htaccess editor menu causes it to edit my own hand-coded file and shuffle lines around to an order IT likes to see them in for use with its own tools. This is breaking the site with or without the Cache-Control lines.
I’ll try testing things one more time, and if all goes well this problem will be solved.