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

2022-08-30 17:12:40

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

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

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

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


答案 1

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

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

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


推荐