Shopify Free Trial Apply
Shopify 60天试用
Shopify 14天试用

Add Expires headers

Expires headers 告诉浏览器是否应该从服务器请求一个特定的文件或者是否应该从浏览器的缓存抓住它。Expires headers 的设计目的是希望使用缓存来减少HTTP requests的数量,从而减少HTTP相应的大小。

Expires headers 中的 Expires 说明了 Expires headers 是有时间限制的,只有在这个指定的时间期限内,浏览器才会从缓存读取数据,而超过这个时间期限,再次访问同一个页面时浏览器还是会向服务器发起  HTTP requests,从服务器端下载页面所需的文件。
 
HTML 文件不要设置 Expires headers。实际的开发经验告诉我,给HTML文件添加 Expires headers 会带来很多的麻烦。即便你要添加  Expires headers,也尽量设置较短的过期时间。这一点在 PageSpeed 的 Leverage browser caching 规则中也明确提到了:

In general, HTML is not static, and shouldn’t be considered cacheable.

知道要缓存哪些资源文件后,接着就是预判这些文件的变更频率,设置合适的过期时间。还是前面的原则,变更频繁的 Expire 时间就越短,不怎么变动的就可以设置长的过期时间,也就是落实“永不过期”的原则。
 
接下来就是在服务器端设置 Expires headers 了,这里以Apache服务器为例,我们在 .htaccess 文件中配置(.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>
 
1
2018-03-27

0 个评论

要回复文章请先登录注册