Cloudflare正式支持HTTP Vary头
My comment on We just shipped support for the ugliest part of HTTP: Vary — Hacker News. I've been wanting this from Cloudflare for years . \n The classic problem here is if yo
Cloudflare正式支持HTTP Vary头
Cloudflare 正式在所有计划下推出 Vary 头支持。这是 HTTP 协议中被长期忽视的机制。那些使用 Accept、Accept-Language 或 Accept-Encoding 做内容协商的站点,现在无需绕过缓存就能确保浏览器和 API 客户端拿到正确的响应。谁需要它?AI 价格雷达、模型 API 切换工具和订阅路径管理类站点,在高并发 API 调用时,它能直接提升缓存命中率,减少对上游的压力。怎么决策?检查你的接口是否已返回 Vary 头,再在 Cache Rules 中选择 normalize(推荐入门)、passthrough 或 bypass 三种行为之一。
Cloudflare Vary 支持的核心价值
Vary 头的作用是告诉中间缓存(Cloudflare),同一个 URL 可以返回多个有效内容。经典场景是浏览器请求 HTML,API 客户端请求 JSON。
GET /catalog HTTP/1.1
Host: example.com
Accept: text/html
原始服务器返回 HTML,并声明 Vary: Accept。另一个请求用 Accept: application/json,缓存会根据 Accept 值区分不同变体,避免混淆。
之前,Cloudflare 对 Vary 的支持有限(尤其非图片场景),容易导致缓存命中错误。2026 年 9 月 22 日官方博客正式上线新功能,客户无需额外代码即可管理。
如何在 Cache Rules 中配置 Vary
打开 /cache > Cache Rules,为规则添加 Vary 设置。优先选择 normalize 作为默认行为,对 Accept、Accept-Language、Accept-Encoding 等协商头进行标准化处理,让等效请求共享缓存。
配置示例表
| 头名称 | 默认行为 | 适用场景 | 推荐理由 |
|---|---|---|---|
| Accept | normalize | 内容类型协商 | 大量请求值映射到有限响应,共享缓存 |
| Accept-Language | normalize | 多语言内容 | 语言标签差异不影响最终内容 |
| Accept-Encoding | normalize | 压缩方案 | 常见场景,减少变体数量 |
| Cookie / User-Agent | bypass | 个性化或高基数头 | 避免碎片化缓存 |
| Vary: * | bypass | 任意请求字段可能变化 | 总是回源,不缓存 |
使用 normalize 时,Cloudflare 会规范化请求头值后匹配缓存;passthrough 则严格保留原始字节用于匹配;bypass 则不存储响应。你可以为每个头单独设置,也用默认行为覆盖未列出的。
实际走法:从配置到缓存命中
1. 确保原始服务器在响应中正确返回 Vary: Accept, Accept-Language 等头(包括错误响应)。
2. 创建 Cache Rule,匹配你的域名和 URL 模式。
3. 在规则中开启 Vary 支持,设置上述行为。
4. 发布后,测试:用不同 Accept 值发起请求,观察缓存键是否正确区分。
完整说明请参考 /guides 中的 Cache Rules 文档。
延伸阅读
风险与边界
代理服务(包括 Cloudflare)有自己的实现边界。使用时请以官方文档和站点当日数据为准,未必实时同步。非法律意见,仅供参考。
English summary
Cloudflare has officially enabled full support for the HTTP Vary header across all plans. This mechanism allows the same URL to serve multiple valid representations, such as HTML for browsers and JSON for APIs, without mixing them in cache. The classic problem—caching the wrong format—is now solvable using Cache Rules with three actions: normalize (recommended for negotiation headers), passthrough (exact matching), or bypass (personalized content). In practice, normalize reduces cache fragmentation for equivalent requests while preserving correctness. Sites using this for AI pricing radars, model API switching tools, or subscription path management can see higher hit rates and lower origin load. Configure via Cache Rules > Vary settings, test with sample requests, and always verify with official sources as implementations may evolve. This update addresses years of interoperability issues in content negotiation.