23

我在我的网站上运行 Google PageSpeed,它告诉我需要
“指定缓存验证器”。

以下资源缺少缓存验证器。未指定缓存验证器的资源无法有效刷新。指定 Last-Modified 或 ETag 标头以启用以下资源的缓存验证:

...然后它列出了图像、CSS、JS 等。

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

将 Last-Modified 日期设置为上次更改资源的时间。如果 Last-Modified 日期在过去足够远,浏览器很可能不会重新获取它。

我的 .htaccess 中有以下内容:

<IfModule mod_headers.c>
    <FilesMatch "\.(bmp|css|flv|gif|ico|jpg|jpeg|js|pdf|png|svg|swf|tif|tiff)$">
        Header set Last-Modified "Tue, 31 Aug 2010 00:00:00 GMT"
    </FilesMatch>
</IfModule>

我究竟做错了什么?

4

3 回答 3

16

我认为您遇到的问题是与Expire:而不是与Last-Modified:. 默认情况下,Apache 会Last-Modified:根据文件日期发送文件头。我建议删除上面的代码并将其替换为以下代码:

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
</IfModule>

尝试一下,如果它不起作用,请尝试添加:

<IfModule mod_headers.c>
    <FilesMatch "\.(bmp|css|flv|gif|ico|jpg|jpeg|js|pdf|png|svg|swf|tif|tiff)$">
        Header set Last-Modified "Mon, 31 Aug 2009 00:00:00 GMT"
    </FilesMatch>
</IfModule>
于 2010-09-04T21:08:08.093 回答
6

为了“设置缓存验证器”,您需要在标题中发送以下内容:

Expires 或者 Cache-Control: max-age

Last-Modified 或者 ETag

因此,例如,在 PHP 中,您可以为 CSS 和 JS 文件添加以下内容:

<filesMatch "\.(js|css)$">
    Header set Expires "Thu, 21 May 2013 20:00:00 GMT"
    Header set Last-Modified "Thu, 21 May 2012 20:00:00 GMT"
</filesMatch>

这将满足 Google 的 Pagespeed 计算器。

于 2012-05-30T10:26:44.807 回答
2

我测试了上述所有代码,但 gtmetrix 排名没有变化。为我的 wordpress 网站使用这个改进的 Cache-Control(指定缓存验证器)排名:

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access plus 1 year"
</IfModule>
## EXPIRES CACHING ##

<ifModule mod_headers.c>
  <filesMatch "\\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
    Header set Cache-Control "max-age=2592000, public"
  </filesMatch>

  <filesMatch "\\.(css)$">
    Header set Cache-Control "max-age=2592000, public"
  </filesMatch>

  <filesMatch "\\.(js)$">
    Header set Cache-Control "max-age=216000, private"
  </filesMatch>

  <filesMatch "\\.(xml|txt)$">
    Header set Cache-Control "max-age=216000, public, must-revalidate"
  </filesMatch>

  <filesMatch "\\.(html|htm|php)$">
    Header set Cache-Control "max-age=1, private, must-revalidate"
  </filesMatch>
</ifModule>

我建议您为您的网站和它自己的文件自定义 max-age 值。

于 2014-10-03T10:37:51.430 回答