设置HTTP缓存过期时间,Google PageSpeed推荐

25

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

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

这个资源从未解释如何实际更改我的HTTP头的过期日期。我应该通过.htaccess来完成这个操作吗?我想尽可能地设置缓存时间(不违反Google一年的最长策略),请问是否有推荐的设置(对于一个自定义的PHP驱动社交网络社区)?

2个回答

30

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


2
这取决于你所说的“很多条件”是什么意思。每个HTTP请求都必须由Web服务器处理条件,因此,如果您考虑到65,000多个条件,那肯定不是一个好主意。 - methode
8
一条小建议:你可以只写“访问时间加一年”,或者更复杂的指令,比如“访问时间加一个月15天2小时”,这样更易于阅读和维护,而不用用秒来表示。 - GeneQ
对于css,Header set Cache-Control "max-age=2692000, public"会覆盖ExpiresByType text/css "access plus 604800 seconds"吗?两者应该是相同的值吗? - David Riccitelli
为什么在FilesMatch指令中要使用双反斜杠"\\"?示例(链接)使用单斜杠。 - DrLightman
为什么您要同时取消ETag和Last-Modified?这里说ETag很重要。 - DrLightman
显示剩余5条评论

1
可以使用htaccess和php来完成。通常情况下,您不会想强制缓存实际的html,因为它是动态数据库驱动的内容(如果需要,可以使用header() php函数)。您要缓存的是外部css和javascript以及图像文件。
请参见此处的.htaccess解决方案: http://www.askapache.com/htaccess/apache-speed-expires.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接