3

我很想实现浏览器缓存并遵循 Google PageSpeed 关于将 Last-Modified 设置为“过去足够远”的数据的建议。我的 .htaccess 中有以下内容:

<IfModule mod_headers.c>
 <FilesMatch "\.(json|pdf|swf|bmp|gif|jpeg|jpg|png|svg|tiff|ico|flv|js)$">
  Header Set Last-Modified "Fri, 01 Jan 2010 12:00:00 GMT"
 </FilesMatch>
</IfModule>

我的服务器上安装了 mod_headers。

不幸的是,Google PageSpeed 仍然抱怨并警告我:

Leverage browser caching

The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:

然后列出 PNG、GIF、JPG 等。Yahoo YSlow 说的基本相同。

查看我应该缓存的资源之一的响应标头,我看到了:

Date:           Tue, 19 Oct 2010 20:12:04 GMT
Server:         Apache/2.2.14 (Ubuntu)
Last-Modified:  Tue, 07 Sep 2010 23:51:33 GMT
Etag:           "2e0e34-2a43-48fb413a96a20"
Accept-Ranges:  bytes
Content-Length: 10819
Content-Type:   image/png

如您所见,Last-Modified 数据与我在 .htaccess 中指定的数据不匹配。

任何想法我做错了什么?

4

3 回答 3

7

删除Last-Modified不是 Google PageSpeed 所要求的。当浏览器请求静态文件时,它希望在您的服务器响应中看到以下标头:

Cache-Control max-age=...
Expires ...

服务器将放置值来代替点。

为此,您只需添加.htaccess以下行:

<IfModule mod_headers.c>
 <FilesMatch "\.(json|pdf|swf|bmp|gif|jpeg|jpg|png|svg|tiff|ico|flv|js)$">
  ExpiresActive On
  ExpiresDefault "access plus 1 year"
  Header append Cache-Control "public"
 </FilesMatch>
</IfModule>

您会看到 Google PageSpeed 停止抱怨。

于 2012-04-07T16:29:36.490 回答
2

您是否考虑过只使用未设置的 Last-Modified?

例子:

<IfModule mod_headers.c>
 <FilesMatch "\.(json|pdf|swf|bmp|gif|jpeg|jpg|png|svg|tiff|ico|flv|js)$">
  Header unset Last-Modified
 </FilesMatch>
</IfModule>

FilesMatch 部分看起来不错,因此它可能只是 Header Set 的一些繁琐之处。地狱,甚至可能区分大小写。尝试Header set代替Header Set

如果这不是您想要的,请告诉我,我会再考虑一下。取消设置应该可以工作,

于 2010-10-20T22:00:38.067 回答
0

这有效:

<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On 
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
于 2014-04-17T20:02:04.663 回答