为什么我的 CDN 缓存了某个文档,而浏览器却没有?

Why does my CDN cache a certain document,but browsers do not?

我有一个 url 上面有一个测试 PDF,这是我的来源: https://powered-by.qbank.se/miso/MISO_Testing_Document279626.pdf

我使用 Microsoft 提供商在 Azure CDN 中设置了源站。 url 是: https://misocdn-fail.azureedge.net/MISO_Testing_Document279626.pdf

当我在源站点上更新 PDF 时,我测试过的所有浏览器都将通过 F5 刷新来恢复新文档,甚至连 ctrl-F5 都没有。但是,CDN 基本上不确定地继续缓存 PDF(根据文档 2 天或直到我清除)

我的问题是,为什么我的 CDN 无法检测到来源和浏览器的更改?

我了解 CDN 缓存,但我不明白浏览器正在做什么来确定此内容是新内容?

为了更好地理解这种现象,观察从直接访问 url 收到的响应 header 是一个好的开始。 一种方法是在您的终端中使用 curl -I <YOUR_URL>

您会看到如下内容:

HTTP/1.1 200 OK
Date: Mon, 01 Oct 2018 09:03:57 GMT
Server: Apache
Last-Modified: Fri, 28 Sep 2018 19:11:57 GMT
ETag: "11ff1-576f33ab4c2a0"
Accept-Ranges: bytes
Content-Length: 73713
Cache-Control: max-age=86400
Expires: Tue, 02 Oct 2018 09:03:57 GMT
Content-Type: application/pdf

在这些 header 中,浏览器使用 Cache-ControlETagLast-Modified 来确定所请求内容的新鲜度。 Cache-Control: max-age=<seconds> 是资源被视为新鲜的最长时间(相对于请求时间)。

现在,根据 Mozilla Developer Network –MDN– Freshness 描述如下:

Once a resource is stored in a cache, it could theoretically be served by the cache forever. Caches have finite storage so items are periodically removed from storage. This process is called cache eviction. On the other side, some resources may change on the server so the cache should be updated. As HTTP is a client-server protocol, servers can't contact caches and clients when a resource changes; they have to communicate an expiration time for the resource. Before this expiration time, the resource is fresh; after the expiration time, the resource is stale. Eviction algorithms often privilege fresh resources over stale resources. Note that a stale resource is not evicted or ignored; when the cache receives a request for a stale resource, it forwards this request with a If-None-Match to check if it is in fact still fresh. If so, the server returns a 304 (Not Modified) header without sending the body of the requested resource, saving some bandwidth.

因此,为了验证缓存资源,如果 ETag header 是资源响应的一部分,浏览器将发出 If-None-Match header。

这是让您的浏览器在直接访问时下载新版本 pdf 的机制。另请注意,这些 header 也出现在来自 CDN url 的请求中,但 CDN 边缘服务器仍在存储您的旧文件。

当谈到 CDN 缓存时,ETagLast-Modified header 不被尊重。只有来自源服务器的 HTTP 响应中的 Cache-Control header 定义了资源的 time-to-live (TTL) 周期。在您的情况下,它是 86400 秒。因此理论上,您的 pdf 的新版本将在通过 CDN link 的第一个请求后的 1 天后提供。 直到那一刻,旧的 pdf 将由 CDN 边缘服务器托管。您可以在 Azure CDN 文档中阅读有关 Azure CDN expiration management 的更多信息。