Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[网络] 4. http 缓存配置怎么设置 #941

Open
qiilee opened this issue Feb 24, 2020 · 0 comments
Open

[网络] 4. http 缓存配置怎么设置 #941

qiilee opened this issue Feb 24, 2020 · 0 comments

Comments

@qiilee
Copy link
Member

qiilee commented Feb 24, 2020

答案:

前端设置 http 缓存,前端设置 html 页面缓存方法:静态的 html 页面想要设置使用缓存需要通过 HTTP 的 META 设置 expires 和 cache-control

设置如下网页元信息:

<meta http-equiv="Cache-Control" content="max-age=7200" />
<meta http-equiv="Expires" content="Mon, 20 Jul 2013 23:00:00 GMT" />

解答:
cache-control:||no-cache||no-store||max-age

1.no-cache:

表面意为“数据内容不被缓存”,而实际数据是被缓存到本地的,只是每次请求时候直接绕过缓存这一环节直接向服务器请求最新资源,由于浏览器解释不一样,

例如 ie 中我们设置了 no-cache 之后,请求虽然不会直接使用缓存,但是还会用缓存数据与服务器数据进行一致性检测(也就是说还是有几率会用到缓存的),

firefox 中则完全无视 no-cache 存在,详细解释见 no-store;

2.no-store:

指示缓存不存储此次请求的响应部分。与 no-cache 比较来说,一个是不用缓存,一个是不存储缓存;按理来说这个设置更加粗暴直接禁用缓存,

但是具体实现起来 浏览器之间差异却特别大,一般不会直接用该字段进行设置,不过 no-store 是为了防止缓存被恶意修改存储路径导致信息被泄露而设置的,

毕竟有它的用处,在 firefox 中实现缓存是通过文件另存为将缓存副本保存到本地,直接利用 no-cache 对其是无效的,如果加上 no-store 设置的话 则可以起到与 no-cache 一样的效果;

即:cache-control:no-cache,no-store;可以确保在支持 http1.1 版本中各大浏览器回车后退刷新无缓存;

再加上 Pragma: no-cache 设置兼容版本 1.0 即可(不过为了防止一致性检测时候的万一我们还是最好加上一致性检测的内容,如下所示几种方式);

3.max-age:

例如 Cache-control: max-age=3;表示此次请求成功后 3 秒之内发送同样请求不会去服务器重新请求,而是使用本地缓存;同样我们如果设置 max-age=0 表示立即抛弃缓存直接发送请求到服务器

以下内容来自:http://www.runoob.com/tags/att-meta-http-equiv.html

HTML http-equiv 属性
HTML meta 标签参考手册 HTML 标签

实例
每隔 30 秒刷新一次文档:

<head>
  <meta http-equiv="refresh" content="30" />
</head>

扩展:

与缓存有关的 header
我们来看看每个 header 的具体含义。

  • Request

Cache-Control: max-age=0 以秒为单位
If-Modified-Since: Mon, 19 Nov 2012 08:38:01 GMT 缓存文件的最后修改时间。
If-None-Match: "0693f67a67cc1:0" 缓存文件的 Etag 值
Cache-Control: no-cache 不使用缓存
Pragma: no-cache 不使用缓存

  • Response

Cache-Control: public 响应被缓存,并且在多用户间共享,  (公有缓存和私有缓存的区别,请看另一节)
Cache-Control: private 响应只能作为私有缓存,不能在用户之间共享
Cache-Control:no-cache 提醒浏览器要从服务器提取文档进行验证
Cache-Control:no-store 绝对禁止缓存(用于机密,敏感文件)
Cache-Control: max-age=60 60 秒之后缓存过期(相对时间)
Date: Mon, 19 Nov 2012 08:39:00 GMT 当前 response 发送的时间
Expires: Mon, 19 Nov 2012 08:40:01 GMT 缓存过期的时间(绝对时间)
Last-Modified: Mon, 19 Nov 2012 08:38:01 GMT 服务器端文件的最后修改时间
ETag: "20b1add7ec1cd1:0" 服务器端文件的 Etag 值

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant