`
wuhua
  • 浏览: 2095354 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

HTTP Cache 学习

    博客分类:
  • HTTP
阅读更多

http协议里控制浏览器缓存的头有三个Cache-Control,Expires,Last-Modified
对于静态页面还有Etag。
一、先来看第一种情况:apache 静态页面
apache发送给客户端的静态页面一般包含Last-Modified和Etag,这两个标签的值来自静态文件的修改时间和inode,
下面是截取得apache返回客户端的头
---------
Last-Modified: Fri, 26 Jan 2007 01:53:34 GMT
ETag: "3f9f640-318-cb9f8380"
---------
搜索引擎之所以喜欢静态文件是因为有这两个标识,可以判断文件是否更新过

二、PHP等动态页面
由于php是动态生成的,它的内容是不能根据php程序的时间来确定最后修改日期,所以默认php返回客户端的时候补包含任何缓存控制,要想利用好缓存就必须了解缓存机制,和理减少b,s的交互,缩减带宽流量,减轻服务器负担...好处多多

三、缓存控制的具体含义
先解释一下本人经过测试理解的这几个标签的含义
Cache-Control:指定请求和响应遵循的缓存机制。在请求消息或响应消息中设置Cache-Control并不会修改另一个消息处理过程中的缓 存处理过程。请求时的缓存指令包括no-cache、no-store、max-age、max-stale、min-fresh、only-if- cached,响应消息中的指令包括public、private、no-cache、no-store、no-transform、must- revalidate、proxy-revalidate、max-age。各个消息中的指令含义如下:
Public指示响应可被任何缓存区缓存。
Private指示对于单个用户的整个或部分响应消息,不能被共享缓存处理。这允许服务器仅仅描述当用户的部分响应消息,此响应消息对于其他用户的请求无效。
no-cache指示请求或响应消息不能缓存
no-store用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存。
max-age指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应。
min-fresh指示客户机可以接收响应时间小于当前时间加上指定时间的响应。
max-stale指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。
php用法:
在输出之前用header(),(如果使用ob_start()可以将header放在程序任意地方)
header('Cache-Control: max-age=8');
max-age=8表示最大生存期8秒,超过8秒浏览器必须去服务器重新读取,这个时间是以用户的读取页面开始计时的,而Expires是绝对时间。
Expires:缓存过期的绝对时间,如果过了它指定的那个时间点,浏览器就不认缓存了,要去服务器重新请求一份最新的。

Last-Modified:文档的最后修改时间,它的妙用就是:1 如果是静态文件,客户端会发上来它缓存里的时间,apache会来比对,如果发现没有修改就直接返回一个头,状态码是304,字节数非常少,(高级版本还会增加比较Etag来确定文件是否变化)
2 php动态文件: 客户端发上比对时间,php会判断是否修改,如果修改时间相同,就只会返回1024字节,至于为什么返回1024不得而知,如果你 的php生成的文件非常大,它也只返回1024,所以比较省带宽,客户端会根据服务器端发过来的修改时间自动从缓存文件里显示。

注:如果没有Last-Modified头,Cache-Control和Expires也是可以起作用的,但每次请求要返回真实的文件字节数,而不是1024

四、HOW ?
静态页面不用去管它了,如果想更好的控制静态页面的缓存,apache有几个模块可以很好的控制,这里不讨论
php页面:
这里分两种:1 不经常改动的页面,类似新闻发布,这类页面的特点:第一次发布之后会有几次改动,随着时间推移基本不会再修改。控制策略应该是:1第一次 发布之发送Last-Modified,max-age设定1天,修改过之后更新Last-Modified,max-age时间随着修改次数正常。这样 似乎比较繁琐,还要记录修改次数,也可以预计一下下次可能的修改时间用Expires指定到大概时间过期
php代码:
//header('Cache-Control: max-age=86400');//缓存一天
header('Expires: Mon, 29 Jan 2007 08:56:01 GMT');//指定过期时间
header('Last-Modified: '.gmdate('D, d M Y 01:01:01',$time).' GMT');//格林尼治时间,$time是文件添加时候的时间戳
2 经常改动的页面   类似bbs,论坛程序,这种页面更新速度比较快,缓存的主要作用是防止用户频繁刷新列表,导致服务器数据库负担,既要保证更新的及时性,也要保证缓存能被利用
这里一般用Cache-Control来控制,根据论坛的发帖的频率灵活控制max-age。
header('Cache-Control: max-age=60');//缓存一分钟
header('Last-Modified: '.gmdate('D, d M Y 01:01:01',$time).' GMT');//格林尼治时间,$time是帖子的最后更新时间戳

五 额外
1 刷新,转到,强制刷新的区别
浏览器上有刷新和转到按键,有的浏览器支持用ctrl+F5强制刷新页面,它们的区别是什么?
转到:用户点击链接就是转到,它完全使用缓存机制,如果有Last-Modified那么不会和服务器通讯,用抓包工具可以查看到发送字节是0byte,如果缓存过期,那么它会执行F5刷新的动作。
刷新(F5):这种刷新也是根据缓存是否有Last-Modified来决定,如果有会转入304或1024(php),如果没有最后更新时间那么去服务器读取,返回真实文档大小
强制刷新:完全抛弃缓存机制,去服务器读取最新文档,向服务器发送的header如下
Cache-Control: no-cache

2 调试工具
查看浏览器和服务器交互比较好的工具是httpwatch pro,现在的版本4.1,支持ie7
还有别的代理抓包工具可以分析,http debugging。没用过,还有tcp抓包工具,2000自带的network monitor不过不是专门针对http的比较难用

六 声明
本文作者保留所有权力,允许被自由查看和转载,但必须指明作者(Ash)和源网址(www.cosrc.com);不允许商用

 

下面是HTTP 协议 E文原版

 

 Cache-Control

   The general-header field "Cache-Control" is used to specify
   directives that MUST be obeyed by all caches along the request/
   response chain.  The directives specify behavior intended to prevent
   caches from adversely interfering with the request or response.
   Cache directives are unidirectional in that the presence of a
   directive in a request does not imply that the same directive is to
   be given in the response.

      Note that HTTP/1.0 caches might not implement Cache-Control and
      might only implement Pragma: no-cache (see Section 3.4).

   Cache directives MUST be passed through by a proxy or gateway
   application, regardless of their significance to that application,
   since the directives might be applicable to all recipients along the
   request/response chain.  It is not possible to target a directive to
   a specific cache.









Fielding, et al.       Expires September 10, 2009              [Page 17]

Internet-Draft              HTTP/1.1, Part 6                  March 2009


     Cache-Control   = "Cache-Control" ":" OWS Cache-Control-v
     Cache-Control-v = 1#cache-directive

     cache-directive = cache-request-directive
        / cache-response-directive

     cache-extension = token [ "=" ( token / quoted-string ) ]

3.2.1.  Request Cache-Control Directives

     cache-request-directive =
          "no-cache"
        / "no-store"
        / "max-age" "=" delta-seconds
        / "max-stale" [ "=" delta-seconds ]
        / "min-fresh" "=" delta-seconds
        / "no-transform"
        / "only-if-cached"
        / cache-extension

   no-cache

      The no-cache request directive indicates that a stored response
      MUST NOT be used to satisfy the request without successful
      validation on the origin server.

   no-store

      The no-store request directive indicates that a cache MUST NOT
      store any part of either this request or any response to it.  This
      directive applies to both non-shared and shared caches.  "MUST NOT
      store" in this context means that the cache MUST NOT intentionally
      store the information in non-volatile storage, and MUST make a
      best-effort attempt to remove the information from volatile
      storage as promptly as possible after forwarding it.

      This directive is NOT a reliable or sufficient mechanism for
      ensuring privacy.  In particular, malicious or compromised caches
      might not recognize or obey this directive, and communications
      networks may be vulnerable to eavesdropping.

   max-age

      The max-age request directive indicates that the client is willing
      to accept a response whose age is no greater than the specified
      time in seconds.  Unless max-stale directive is also included, the
      client is not willing to accept a stale response.




Fielding, et al.       Expires September 10, 2009              [Page 18]

Internet-Draft              HTTP/1.1, Part 6                  March 2009


   max-stale

      The max-stale request directive indicates that the client is
      willing to accept a response that has exceeded its expiration
      time.  If max-stale is assigned a value, then the client is
      willing to accept a response that has exceeded its expiration time
      by no more than the specified number of seconds.  If no value is
      assigned to max-stale, then the client is willing to accept a
      stale response of any age. [[anchor15: of any staleness? --mnot]]

   min-fresh

      The min-fresh request directive indicates that the client is
      willing to accept a response whose freshness lifetime is no less
      than its current age plus the specified time in seconds.  That is,
      the client wants a response that will still be fresh for at least
      the specified number of seconds.

   no-transform

      The no-transform request directive indicates that an intermediate
      cache or proxy MUST NOT change the Content-Encoding, Content-Range
      or Content-Type request headers, nor the request entity-body.

   only-if-cached

      The only-if-cached request directive indicates that the client
      only wishes to return a stored response.  If it receives this
      directive, a cache SHOULD either respond using a stored response
      that is consistent with the other constraints of the request, or
      respond with a 504 (Gateway Timeout) status.  If a group of caches
      is being operated as a unified system with good internal
      connectivity, such a request MAY be forwarded within that group of
      caches.

















Fielding, et al.       Expires September 10, 2009              [Page 19]

Internet-Draft              HTTP/1.1, Part 6                  March 2009


3.2.2.  Response Cache-Control Directives

     cache-response-directive =
          "public"
        / "private" [ "=" DQUOTE 1#field-name DQUOTE ]
        / "no-cache" [ "=" DQUOTE 1#field-name DQUOTE ]
        / "no-store"
        / "no-transform"
        / "must-revalidate"
        / "proxy-revalidate"
        / "max-age" "=" delta-seconds
        / "s-maxage" "=" delta-seconds
        / cache-extension

   public

      The public response directive indicates that the response MAY be
      cached, even if it would normally be non-cacheable or cacheable
      only within a non-shared cache.  (See also Authorization, Section
      3.1 of [Part7], for additional details.)

   private

      The private response directive indicates that the response message
      is intended for a single user and MUST NOT be stored by a shared
      cache.  A private (non-shared) cache MAY store the response.

      If the private response directive specifies one or more field-
      names, this requirement is limited to the field-values associated
      with the listed response headers.  That is, the specified field-
      names(s) MUST NOT be stored by a shared cache, whereas the
      remainder of the response message MAY be.

      Note: This usage of the word private only controls where the
      response may be stored, and cannot ensure the privacy of the
      message content.

   no-cache

      The no-cache response directive indicates that the response MUST
      NOT be used to satisfy a subsequent request without successful
      validation on the origin server.  This allows an origin server to
      prevent caching even by caches that have been configured to return
      stale responses.

      If the no-cache response directive specifies one or more field-
      names, this requirement is limited to the field-values assosicated
      with the listed response headers.  That is, the specified field-



Fielding, et al.       Expires September 10, 2009              [Page 20]

Internet-Draft              HTTP/1.1, Part 6                  March 2009


      name(s) MUST NOT be sent in the response to a subsequent request
      without successful validation on the origin server.  This allows
      an origin server to prevent the re-use of certain header fields in
      a response, while still allowing caching of the rest of the
      response.

      Note: Most HTTP/1.0 caches will not recognize or obey this
      directive.

   no-store

      The no-store response directive indicates that a cache MUST NOT
      store any part of either the immediate request or response.  This
      directive applies to both non-shared and shared caches.  "MUST NOT
      store" in this context means that the cache MUST NOT intentionally
      store the information in non-volatile storage, and MUST make a
      best-effort attempt to remove the information from volatile
      storage as promptly as possible after forwarding it.

      This directive is NOT a reliable or sufficient mechanism for
      ensuring privacy.  In particular, malicious or compromised caches
      might not recognize or obey this directive, and communications
      networks may be vulnerable to eavesdropping.

   must-revalidate

      The must-revalidate response directive indicates that once it has
      become stale, the response MUST NOT be used to satisfy subsequent
      requests without successful validation on the origin server.

      The must-revalidate directive is necessary to support reliable
      operation for certain protocol features.  In all circumstances an
      HTTP/1.1 cache MUST obey the must-revalidate directive; in
      particular, if the cache cannot reach the origin server for any
      reason, it MUST generate a 504 (Gateway Timeout) response.

      Servers SHOULD send the must-revalidate directive if and only if
      failure to validate a request on the entity could result in
      incorrect operation, such as a silently unexecuted financial
      transaction.

   proxy-revalidate

      The proxy-revalidate response directive has the same meaning as
      the must-revalidate response directive, except that it does not
      apply to non-shared caches.

   max-age



Fielding, et al.       Expires September 10, 2009              [Page 21]

Internet-Draft              HTTP/1.1, Part 6                  March 2009


      The max-age response directive indicates that response is to be
      considered stale after its age is greater than the specified
      number of seconds.

   s-maxage

      The s-maxage response directive indicates that, in shared caches,
      the maximum age specified by this directive overrides the maximum
      age specified by either the max-age directive or the Expires
      header.  The s-maxage directive also implies the semantics of the
      proxy-revalidate response directive.

   no-transform

      The no-transform response directive indicates that an intermediate
      cache or proxy MUST NOT change the Content-Encoding, Content-Range
      or Content-Type response headers, nor the response entity-body.

3.2.3.  Cache Control Extensions

   The Cache-Control header field can be extended through the use of one
   or more cache-extension tokens, each with an optional value.
   Informational extensions (those that do not require a change in cache
   behavior) can be added without changing the semantics of other
   directives.  Behavioral extensions are designed to work by acting as
   modifiers to the existing base of cache directives.  Both the new
   directive and the standard directive are supplied, such that
   applications that do not understand the new directive will default to
   the behavior specified by the standard directive, and those that
   understand the new directive will recognize it as modifying the
   requirements associated with the standard directive.  In this way,
   extensions to the cache-control directives can be made without
   requiring changes to the base protocol.

   This extension mechanism depends on an HTTP cache obeying all of the
   cache-control directives defined for its native HTTP-version, obeying
   certain extensions, and ignoring all directives that it does not
   understand.

   For example, consider a hypothetical new response directive called
   "community" that acts as a modifier to the private directive.  We
   define this new directive to mean that, in addition to any non-shared
   cache, any cache that is shared only by members of the community
   named within its value may cache the response.  An origin server
   wishing to allow the UCI community to use an otherwise private
   response in their shared cache(s) could do so by including

     Cache-Control: private, community="UCI"



Fielding, et al.       Expires September 10, 2009              [Page 22]

Internet-Draft              HTTP/1.1, Part 6                  March 2009


   A cache seeing this header field will act correctly even if the cache
   does not understand the community cache-extension, since it will also
   see and understand the private directive and thus default to the safe
   behavior.

   Unrecognized cache directives MUST be ignored; it is assumed that any
   cache directive likely to be unrecognized by an HTTP/1.1 cache will
   be combined with standard directives (or the response's default
   cacheability) such that the cache behavior will remain minimally
   correct even if the cache does not understand the extension(s).

3.3.  Expires

   The entity-header field "Expires" gives the date/time after which the
   response is considered stale.  See Section 2.3 for further discussion
   of the freshness model.

   The presence of an Expires field does not imply that the original
   resource will change or cease to exist at, before, or after that
   time.

   The field-value is an absolute date and time as defined by HTTP-date
   in Section 3.2.1 of [Part1]; it MUST be sent in rfc1123-date format.

     Expires   = "Expires" ":" OWS Expires-v
     Expires-v = HTTP-date

   For example

     Expires: Thu, 01 Dec 1994 16:00:00 GMT

      Note: if a response includes a Cache-Control field with the max-
      age directive (see Section 3.2.2), that directive overrides the
      Expires field.  Likewise, the s-maxage directive overrides Expires
      in shared caches.

   HTTP/1.1 servers SHOULD NOT send Expires dates more than one year in
   the future.

   HTTP/1.1 clients and caches MUST treat other invalid date formats,
   especially including the value "0", as in the past (i.e., "already
   expired").

 

http://www.ietf.org/internet-drafts/draft-ietf-httpbis-p6-cache-06.txt

分享到:
评论

相关推荐

    http cache-control详解

    关于http cache-control详解,对学习http有很大的帮助

    Symfony2框架学习笔记之HTTP Cache用法详解

    主要介绍了Symfony2框架HTTP Cache用法,结合实例形式分析了Symfony框架HTTP缓存的相关使用技巧,需要的朋友可以参考下

    Cache-control使用Cache-control:private学习笔记

    网页缓存由 HTTP消息头中的Cache-control控制,常见取值有private、no-cache、max-age、must- revalidate等,默认为private

    Cache相关资料手册

    学习Cache的相关资料,配合博文http://t.csdnimg.cn/byxRb学习,包含一些手册资料

    jsp学习项目

    <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta ...

    小程序 Java的HTTP代理服务器 Smart Cache(源码).zip

    免责声明:资料部分来源于合法的互联网渠道收集和整理,部分自己学习积累成果,供大家学习参考与交流。收取的费用仅用于收集和整理资料耗费时间的酬劳。 本人尊重原创作者或出版方,资料版权归原作者或出版方所有,...

    Nginx全套学习指南

    第9章 Nginx的Web缓存服务与新浪网的开源NCACHE模块 第10章 Nginx在国内知名网站中的应用案例 第11章 Nginx的非典型应用实例 第12章 Nginx的核心模块 第13章 Nginx的标准HTTP模块 第14章 Nginx的其他HTTP模块 第15章...

    SqlSugar框架的学习使用

    1、优越的性能,查询使用 reflection.emit 创建IL语言+委托绑定 然后对该对象进行 cache ,datareader直接赋值给cache对象,高性能拉姆达解析,总体性能媲美 http://ADO.NET ,查询速度稍慢于datareader但稍快于...

    Ngnix学习指南电子版

    第9章 Nginx的Web缓存服务与新浪网的开源NCACHE模块 第10章 Nginx在国内知名网站中的应用案例 第11章 Nginx的非典型应用实例 第12章 Nginx的核心模块 第13章 Nginx的标准HTTP模块 第14章 Nginx的其他HTTP模块 第15章...

    【白雪红叶】JAVA学习技术栈梳理思维导图.xmind

    关于java程序员发展需要学习的路线整理集合 技术 应用技术 计算机基础知识 cpu mem disk net 线程,进程 第三方库 poi Jsoup zxing Gson 数据结构 树 栈 链表 队列 图 操作系统 linux 代码控制...

    90Days:这是一个学习小站,以后每天都会上传学习笔记

    2015.02.08#Too Young Too SimpleOCProgrammingWithObjective-CiOS Programming Pushing The LimitsOC Programming The Big Nerd Ranch Guide:runtime:Image Handle, Cache, NSOperation, Block):NSOperation, HTTP,...

    Varnish配置教程和学习资料合集

    教程名称: Varnish配置教程和学习资料合集【】HTTP加速器varnish安装部署【】varnish cache 配置使用ChinaUnix【】varnish 原理【】Varnish-vcl的配置【】varnish配置实例 资源太大,传百度网盘了,链接在附件中,...

    chinese-learner:一个学习普通话和汉字笔顺的桌面网络应用程序

    中文学习者 一个用于学习中文及其汉字笔顺的桌面网络应用程序。 用法 默认情况下,当您执行npm start ,应用程序会在http://localhost:1275 。 您可以在index.js文件中更改端口和所有其他 Express 设置。 当前字符...

    Internetworking IPv6 with Cisco Routers

    想要学习IPv6的,这本书我觉得真的很好,希望大家都可以看看。 先贴一个目录给大家看看: Chapter 1: Introduction Overview, Why IPv6, Why a new address scheme, Best Effort: is it enough, Requisites to be ...

    微服注册中心搭建与服务注册

    开发环境:IDEA集成开发工具,JDK 1.8 使用步骤:下载资源后解压项目,使用IDEA导入项目文件。 ... ... 3. 在浏览器中打开一个窗口的地址栏,输入:...使用对象:想学习使用Spring 5.x版本实现的Spring Cloud编程的小白。

    springboot学习思维笔记.xmind

    springboot学习笔记 spring基础 Spring概述 Spring的简史 xml配置 注解配置 java配置 Spring概述 Spring的模块 核心容器CoreContainer Spring-Core Spring-Beans ...

    AngualrJS中每次$http请求时的一个遮罩层Directive

    AngularJS是一款非常强大的前端MVC框架。接下来通过本文给大家介绍AngualrJS中每次$http请求时的一个遮罩层Directive,本文非常具有参考借鉴价值,特此分享供大家学习

    安卓毕业设计app项目源码6-projectOfGjf:我的业余学习项目-贪吃蛇小游戏、大雨吃小鱼<

    以下总结要解决的问题(自己需要学习的知识点) 移动端适配方案(rem写法及转换) html: <meta http-equiv="Expires" content="0" /> <meta http-equiv="Cache-Control" content="no-cache" /> <meta ...

    百度贴吧小偷采集 v1.0 已优化

     必须把 cache 目录 设置为 777  WINDOWS 则不影响。  测试环境:LNMP  程序可以放在任意目录。  仅供测试学习之用,template 目录可以自己修改模板、统计代码可以加在 template/tfooter.tpl.php  多余的...

    SkyEye教程

    目前已经在在基于Atmel91X40 CPU的开发板上实现了网络芯片8019AS扩展,并增加了μC/OS-II和μClinux的网络驱动程序,已经支持大量的网络应用程序,如LwIP (一个TCP/IP协议栈实现)、nfs server/clinet、http server...

Global site tag (gtag.js) - Google Analytics