25

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

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

此资源从未解释如何实际更改我的 http 标头的到期日期。我是否通过 .htaccess 执行此操作?我想尽可能长时间地设置缓存(不违反谷歌的最多一年的政策)。

任何关于推荐设置的建议(对于自定义 php 驱动的社交网络社区)将不胜感激。

4

2 回答 2

29

在您的根目录的 .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>

并遵循:

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

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

于 2010-04-20T16:34:17.170 回答
1

它可以用 htaccess 和 php 来完成。通常,您不想强制缓存实际的 html,因为它是动态数据库驱动的内容(header()如果需要,可以使用 php 函数完成)。您要缓存的是外部 css 和 javascript 以及图像文件。

请参阅此处了解 .htaccess 解决方案:http ://www.askapache.com/htaccess/apache-speed-expires.html

于 2010-04-20T16:23:08.883 回答