(译)使用 meta 禁用浏览器缓存

原文

一个最简单的支持大部分主流浏览器的 headers 集如下:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
  • Cache-Control 作用于 HTTP1.1

HTTP1.1中启用Cache-Control 来控制页面的缓存与否,这里介绍几个常用的参数:

  • no-cache,浏览器和缓存服务器都不应该缓存页面信息;
  • public,浏览器和缓存服务器都可以缓存页面信息;
  • no-store,请求和响应的信息都不应该被存储在对方的磁盘系统中;
  • must-revalidate,对于客户机的每次请求,代理服务器必须想服务器验证缓存是否过时
  • Pragma 作用于 HTTP 1.0

HTTP1.0 中通过 Pragma 控制页面缓存,通常设置的值为 no- cache,不过这个值不这么保险,通常还加上 Expires 置为 0 来达到目的。但是如我们刻意需要浏览器或缓存服务器缓存住我们的页面这个值则要设置为 Pragma

  • Expires 作用于 proxies

表示存在时间,允许客户端在这个时间之前不去检查(发请求),等同 max-age 的 效果。但是如果同时存在,则被 Cache-Controlmax-age 覆盖。 格式: Expires :时间,后面跟一个时间或者日期,超过这个时间后缓存失效。也就是浏览器发出请求之前,会检查这个时间是否失效,若失效,则浏览器会重新发出请求。

HTML

通过添加 标签来禁止浏览器缓存(代码必须包含在 标签中)




其他环境的设置

  • .htaccess (Apache)

  Header set Cache-Control "no-cache, no-store, must-revalidate"
  Header set Pragma "no-cache"
  Header set Expires 0

  • Java Servlet
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
  • PHP
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
  • ASP
Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate"
Response.addHeader "Pragma", "no-cache"
Response.addHeader "Expires", "0"
  • ASP.NET
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
  • Ruby on Rails
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
  • Python on Flask
resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "0"
  • Google Go
responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
responseWriter.Header().Set("Pragma", "no-cache")
responseWriter.Header().Set("Expires", "0")

Resources

  • http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9

  • http://stackoverflow.com/a/2068407

  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

后记

上述方案对于 Safari 并无鸟用,一种比较正规的方案是:

    $(window).bind("pageshow", function (event) {
        if (event.originalEvent.persisted) {
            window.location.reload();
        }
    });

你可能感兴趣的:((译)使用 meta 禁用浏览器缓存)