使用哪一个:过期标头、上次修改标头或 ETag
我在 Apache 上运行 PHP,并且对如何实现服务器端缓存以使网站加载速度更快感到困惑。
Expires
、Last-Modified
和 ETag
标头之间有什么区别?在什么情况下应使用哪一个?
I am running PHP on Apache, and am confused about how to implement server-side caching, in order to make the site load faster.
What is the difference between the Expires
, Last-Modified
and ETag
headers, and which one should be used in what situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Expires
和Cache-Control
是“强缓存标头”Last-Modified
和ETag
是“弱缓存标头”首先,浏览器检查
Expires/Cache-Control
以确定是否向服务器发出请求。如果必须发出请求,它将在 HTTP 请求中发送
Last-Modified/ETag
。如果文档的Etag
值与此匹配,服务器将发送 304 代码而不是 200,并且不发送任何内容。浏览器将从其缓存中加载内容。我建议使用强缓存标头之一和弱缓存标头之一。
另请参阅:
Expires
andCache-Control
are "strong caching headers"Last-Modified
andETag
are "weak caching headers"First the browser checks
Expires/Cache-Control
to determine whether or not to make a request to the servers.If it has to make a request, it will send
Last-Modified/ETag
in the HTTP request. If theEtag
value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.I recommend using one of the strong caching headers, along with one of the weak caching headers.
See also:
您可以结合使用
Expires
标头,但不管其他两个标头如何。它受到代理和浏览器缓存的普遍支持。ETag
和Last-Modified
标记之间的区别更多是语义上的。 ETag 对客户端来说是不透明的。它通常是一个校验和。而 Last-Modified 标头可以由客户端解释。据了解,最后修改的时间戳是线性工作的。如果浏览器使用
If-Unmodified-Since
请求资源,则过去的各种时间戳都可以匹配此类条件。如果您的页面经常更改,那么“上次修改时间”时间戳可能会很有用。另一方面,ETag 方法使客户端为每个资源保存最后一个指纹。 (我不确定浏览器缓存是否记住多个 ETag)。根据请求,仅列出一个或几个可能的
If-None-Match
令牌。这可能意味着更多的失误。此外,您必须比较多个校验和,而使用“上次修改时间”时间戳,您可以进行算术比较。ETag 的真正优势在于您可以可靠地比较指纹。 Last-Modified 时间戳有点模糊,因为它们不验证实际页面内容是否更改。
另请参阅:
You can use the
Expires
header in conjunction but regardless of the other two. It's universally supported by proxies and browser caches.The difference between
ETag
andLast-Modified
stamps is more semantic. ETags are opaque to clients. It's usually a checksum. Whereas a Last-Modified header can be interpreted by clients. It's understood that the last modified timestamp works linearly.If a browser requests a resource with
If-Unmodified-Since
, then a wide range of timestamps in the past can match such a condition. If your pages change frequently then a Last-Modified timestamp might be advantageous.The ETag approach, on the other hand, leads to clients that save one last fingerprint per resource. (I'm not sure if browser caches remember multiple ETags). On requests, only one or a few possible
If-None-Match
tokens are listed. This might mean more misses. Also, you have to compare multiple checksums, whereas with a Last-Modified timestamp you could have an arithmetic comparison.The real advantage of ETags is that you can reliably compare fingerprints. The Last-Modified timestamps are a bit more vague, as they don't verify if the actual page content changed.
See also: