【问题标题】:Understand Etags HTTP Header了解 Etags HTTP 标头
【发布时间】:2011-07-02 06:04:22
【问题描述】:

我正在使用具有如下功能的缓存库。它试图从第 5 行的请求中获取 eTag,但从未设置 eTag。

REQUEST 什么时候会有电子标签?以及如何设置它们?

谢谢。

public function isNotModified(Request $request)
{
    $lastModified = $request->headers->get('If-Modified-Since');

    $notModified = false;
    if ($etags = $request->getEtags()) {
        $notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
    } elseif ($lastModified) {
        $notModified = $lastModified == $this->headers->get('Last-Modified');
    }

    if ($notModified) {
        $this->setNotModified();
    }

    return $notModified;
}

【问题讨论】:

  • ETag if 只有一个响应头字段:“ETag 响应头字段为请求的变体提供实体标签的当前值。”
  • 相关:stackoverflow.com/questions/5081397/… 实际上,ETag 仅出现在响应标头中。请求中的反标头是 If-None-Match,正如您在其他问题中所回答的那样。

标签: php http outputcache cache-control


【解决方案1】:

ETag header field 仅用于回复:

ETag 响应头字段为请求的变体提供实体标签的当前值。

getEtags 方法可能是来自If-None-Match header field 的标签:

如果任何实体标签与该资源上类似 GET 请求(没有 If-None-Match 标头)的响应中返回的实体的实体标签匹配,或者如果给出“*”并且该资源存在任何当前实体,则服务器不得执行请求的方法,除非需要这样做,因为资源的修改日期与 If- 中提供的日期不匹配请求中的 Modified-Since 标头字段。相反,如果请求方法是 GET 或 HEAD,服务器应该以 304(未修改)响应进行响应,包括匹配的实体之一的缓存相关标头字段(特别是 ETag)。对于所有其他请求方法,服务器必须以状态 412(前提条件失败)进行响应。

这似乎与给定的代码完全匹配(我重新排列了第一句话以适应代码):

//   the server MUST NOT perform the requested method
$notModified = (
    //   if any of the entity tags match the entity tag of the entity that
    //   would have been returned in the response to a similar GET request
    //   (without the If-None-Match header) on that resource
    in_array($this->getEtag(), $etags)
    //   or if "*" is given and any current entity exists for that resource
    || in_array('*', $etags))
    //   unless required to do so because the resource's modification
    //   date fails to match that supplied in an If-Modified-Since header
    //   field in the request.
    && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);

最后一个表达式(!$lastModified || $this->headers->get('Last-Modified') == $lastModified)等价于!($lastModified && $this->headers->get('Last-Modified') != $lastModified),更适合最后一句部分。

【讨论】:

  • 它正在检查 if_none_match 标头。这比我想象的要混乱得多。我只想缓存!
  • @Mike:如果您只想强制浏览器缓存资源,只需将ETagLast-ModifiedExpires 标头添加到响应资源。然后,当后续请求以If-Modified-SinceIf-None-Match 进入时,只需测试它们并通过返回 304 或相关更改的资源进行相应处理。
猜你喜欢
  • 2011-07-02
  • 1970-01-01
  • 2010-09-09
  • 2011-06-04
  • 2012-09-15
  • 2011-06-08
  • 2019-11-13
  • 1970-01-01
  • 2016-05-09
相关资源
最近更新 更多