https://roadmap.sh/guides/http-caching
代理 反向代理
请求方的代理是 代理
响应方的代理是 反向代理
缓存位置
客户端缓存
代理缓存
比如长城宽带什么的ISP, 对热门资源进行缓存, 这样就少交点流量费
反向代理缓存
自己服务器提供的缓存
HTTP header 控制非服务端的缓存
http 1.0 Expires(过期的, 但仍被支持)
http 1.1 Cache-Control
Cache-Control: private
只应该被客户端(浏览器)缓存
Cache-Control: public
客户端和代理都可以缓存
Cache-Control: no-store
禁止缓存
Cache-Control: no-cache
可以被缓存, 但使用前要向服务器端重新验证(会和服务器通信, 但不下载内容)
max-age 缓存秒数
Cache-Control: max-age=3600, public
s-maxage 共享缓存的秒数
优先级高, 会覆盖max-age
Cache-Control: s-maxage=3600, public
must-revalidate 由于网络问题验证失败也不能使用缓存
Cache-Control: max-age=3600, public, must-revalidate
proxy-revalidate 代理级别的缓存由于网络问题验证失败也不能使用缓存
同时指定了no-store 和no-cache, no-store 优先级高(覆盖no-cache)
Cache-Control: no-store, no-cache
等同于Cache-Control: no-store
对于需要验证的缓存 验证过程
未过期请求验证-浏览器发送请求时在http header 中加上
If-None-Match: "abc123xyz"
值叫做Etag
一般用哈希值实现
未过期响应
304 Not Modified
表示缓存没有过期, 有效,
返回http header 和一个空的主体
Last-Modified: Wed, 15 Mar 2019 12:22:21 GMT
缓存内容最后一次更新时间(不是必须的 http header)
过期后请求验证
If-Modified-Since: 日期值(是保存在客户端的Last-Modified 的值, 第一次请求时会得到这个值)
如果内容没跟新过, 返回304
如果更新过, 则返回新内容
另外, SEO 爬虫也会询问内容是否更新
Apache 或 Nginx 会自动处理这些事情, 不用再代码中写http header
比如apache 配置, .htaccess 文件 或者 http.conf 文件
# Cache everything for an year
Header set Cache-Control "max-age=31536000, public"
# Cache any images for one year
<filesMatch ".(png|jpg|jpeg|gif)$">
Header set Cache-Control "max-age=31536000, public"
</filesMatch>
# Cache any CSS and JS files for a month
<filesMatch ".(css|js)$">
Header set Cache-Control "max-age=2628000, public"
</filesMatch>
一些实践套路
静态文件一律缓存一年, 文件名加上版本号(或指纹)
RSS 文件可以缓存几个小时, 但是像npm 库存就不应该有缓存
在响应中添加验证其(如ETag)
不要缓存用户隐私内容
缓存时长差别大的文件别合并, 以便只更新局部
测试服务器提供的缓存表头命令
curl -I http://url.com
λ curl -I <http://bifan.io>
HTTP/1.1 200 OK
Date: Mon, 02 Dec 2019 14:32:59 GMT
Server: Apache/2.4.38 (Ubuntu)
Last-Modified: Thu, 23 May 2019 07:53:38 GMT
ETag: "239-589896135e480"
Accept-Ranges: bytes
Content-Length: 569
Vary: Accept-Encoding
Content-Type: text/html
λ curl -I <https://www.baidu.com>
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: Keep-Alive
Content-Length: 277
Content-Type: text/html
Date: Mon, 02 Dec 2019 14:33:54 GMT
Etag: "575e1f6f-115"
Last-Modified: Mon, 13 Jun 2016 02:50:23 GMT
Pragma: no-cache
Server: bfe/1.0.8.18