设置Google PageSpeed推荐的HTTP缓存过期

pws*_*068 25 php .htaccess caching pagespeed

我使用Google的PageSpeed在我的网站上运行测试,它建议我"利用浏览器缓存"并提供以下资源:

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

此资源从未解释如何实际更改我的http标头的到期日期.我是通过.htaccess做的吗?我想尽可能长时间地设置缓存(不违反Google最近一年的政策).

任何关于推荐设置的建议(对于自定义的PHP驱动的社交网络社区)都将非常感激.

met*_*ode 29

在你的root的.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>
Run Code Online (Sandbox Code Playgroud)

并遵循:

<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>
Run Code Online (Sandbox Code Playgroud)

这是我在我管理的每个属性上使用的完全相同的代码,并为我(和PageSpeed)提供了最令人满意的结果.有人可能会争论具体的规则,这就是为什么我说它满足了,但它确实满足了PageSpeed.

  • 只是一个提示.你可以写"访问加1年"或甚至更复杂的指令,如"访问加1个月15天2小时",这比指令更容易阅读和维护. (8认同)
  • 这取决于"很多条件"是什么意思.Web服务器必须在每个HTTP请求上处理这些条件,因此如果您考虑65,000多个条件,那么这当然不是一个好主意 (2认同)