views:

336

answers:

2

I ran tests on my website using Google's PageSpeed and it recommends that I "Leverage browser caching" and provided the following resource:

http://code.google.com/speed/page-speed/docs/caching.html#LeverageBrowserCaching

This resource never explains how to actually change the expiration date of my http headers. Do I do this through .htaccess? I would like to set the caching for as long as possible (without violating Google's policy of a year max).

Any advice on recommended settings (for a custom php-driven social networking community) would be greatly appreciated.

+1  A: 

It can be done with both htaccess and php. Typically you wouldn't want to force caching the actual html since its dynamic database driven content (it can be done with the header() php function if needed). What you want to cache is external css & javascript, and image files.

See here for an .htaccess solution: http://www.askapache.com/htaccess/apache-speed-expires.html

Mark
+5  A: 

In your root's .htaccess:

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType image/x-icon "access plus 2592000 seconds"
  ExpiresByType image/jpeg "access plus 2592000 seconds"
  ExpiresByType image/png "access plus 2592000 seconds"
  ExpiresByType image/gif "access plus 2592000 seconds"
  ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
  ExpiresByType text/css "access plus 604800 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"
  ExpiresByType text/html "access plus 600 seconds"
  ExpiresByType application/xhtml+xml "access plus 600 seconds"
</IfModule>

And follow by:

<IfModule mod_headers.c>
<FilesMatch "\\.(ico|jpe?g|png|gif|swf)$">
Header set Cache-Control "max-age=2692000, public"
</FilesMatch>
<FilesMatch "\\.(css)$">
Header set Cache-Control "max-age=2692000, public"
</FilesMatch>
<FilesMatch "\\.(js)$">
Header set Cache-Control "max-age=216000, private"
</FilesMatch>
<FilesMatch "\\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</FilesMatch>
Header unset ETag
Header unset Last-Modified
</IfModule>

This is the exact same code I use on every property I manage and offers for me (and PageSpeed) the most satisfying results. One may argue on specific rules, that's why I said that it satisfies me, but it certainly satisfies PageSpeed.

methode
Great, this will certainly give me a template to work with. Does having a lot of conditions in htaccess have much affect on the response time of the server?
pws5068
It depends on what do you mean by "lot of conditions".The conditions have to be processed by the web server on each HTTP request so if you think about 65,000+ conditions, then that's certainly not a good idea
methode