使用 htaccess 设置静态资源的过期时间

Setting expiry on static resources with htaccess

刚刚知道为静态资源设置过期日期可以让您的网站运行速度更快并在排名中跃升。

我的问题是:

  1. 浏览器是否检查静态资源的创建日期?

  2. 如果我在 1 个月前更改 css,服务器会发送新副本并且浏览器会刷新其缓存吗?

这是我添加到 htaccess 的代码:

<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 plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>

来自mod_expires documentation

The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

语法如下:

ExpiresByType type/encoding "base[plus num type] [num type] ..."

where base is one of:

  • access
  • now (equivalent to 'access')
  • modification

The plus keyword is optional. num should be an integer value [acceptable to atoi()], and type is one of:

  • years
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds

所以如果你写:

ExpiresByType image/gif "access plus 1 month"

只要访问者在一个多月内不间断地请求您的文件,即使您修改了它,您的文件也会被缓存。


你应该改为:

ExpiresByType image/gif "modification plus 1 month"

那么你的文件只要没有被修改就会被缓存一个月,否则会更新缓存。