Set HTTP Caching Expiration, Recommended by Google PageSpeed

青春壹個敷衍的年華 提交于 2019-12-18 10:19:43

问题


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:


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 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.




回答2:


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



来源:https://stackoverflow.com/questions/2676744/set-http-caching-expiration-recommended-by-google-pagespeed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!