图标缓存的奇怪行为

Odd Behaviour of Icon Caching

考虑生成 ico 图像的 view

from django.http import HttpResponse
from app.somewhere import Favicon

# View URL: `/<str:colour>.ico`
def favicon( request, colour ):
    response = HttpResponse(
        Favicon.render( colour ),
        status=200
    )

    response['Content-Type'] = 'image/x-icon'
    response['Cache-Control'] = 'public, max-age=31536000'

    return response

Favicon.render() returns有效的字节流,不用关注

这是我的 HTML 文档的 head 中的一个 link 元素:

<link rel=icon href=/7f9fa4.ico>

现在问题来了:为什么每次我重新加载页面时,我的浏览器 Chromium 73 都会向 /7f9fa4.ico 发出请求,而不是从中检索图标缓存?如果我将在新选项卡中打开 /7f9fa4.ico,将向服务器发送第一次请求,然后我的浏览器将从缓存中检索图像;现在告诉我 browser-caching 系统出了什么问题。


这是一个请求(cookies和首选项被省略):

GET /7f9fa4.ico HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36
Referer: http://localhost:8000/

这些是回应 headers:

HTTP/1.1 200 OK
Date: Mon, 03 Jun 2019 07:03:58 GMT
Server: WSGIServer/0.2 CPython/3.6.8
Content-Type: image/x-icon
Cache-Control: public, max-age=31536000
X-Frame-Options: SAMEORIGIN
Content-Length: 196

控制台输出(如果有帮助的话):

[05/Jun/2019 09:17:42] "GET /7f9fa4.ico HTTP/1.1" 200 196

此外,如果我要从 head 中删除 link 元素,浏览器每次都会向 /favicon.ico 发出请求(在我的例子中只是镜像 /ffffff.ico)重新加载页面效果相同。

您可能会发现发出此请求是为了验证缓存的内容。我注意到您发送到服务器的请求有 Cache-Control: no-cachePragma: no-cache.

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

no-cache Forces caches to submit the request to the origin server for validation before releasing a cached copy.

因此它强制缓存提交验证请求。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Pragma#Directives

no-cache Same as Cache-Control: no-cache. Forces caches to submit the request to the origin server for validation before releasing a cached copy.

这些说明浏览器在使用缓存图标之前应该向您的服务器发送 "validation" 请求。