跳转到内容
搜索文档

Workers 如何与 Cache Rules 交互

最后更新 查看 MarkdownAgent 设置

当在同一请求上同时使用 Cache RulesWorkers 时,Worker 的缓存设置优先——但前提是启用了所需的兼容性标志

您的 Workers 脚本可以覆盖 Cache Rules 行为,无论请求是针对通过 Cloudflare 代理的域名还是未代理的域名。例如,如果 Cache Rule 配置为对 example.com/foo 绕过缓存,但您的 Workers 脚本在 fetch() 请求的 cf 对象中设置 cacheEverything: true,Worker 的设置优先,响应被缓存。

优先级顺序

缓存行为由以下优先级顺序决定:

  1. Workers 脚本设置
  2. Cache rules
  3. Page rules

Workers 覆盖 Cache Rules,Cache Rules 覆盖 Page Rules。当同一级别的多个规则匹配同一请求时,对于任何冲突的设置,最后匹配的规则获胜

兼容性标志

覆盖行为由兼容性标志控制——选择 Worker 进入特定运行时行为的配置设置。有两个标志,因为 Workers 有两种与缓存交互的方式:

  • 对于 Fetch API(带 cf 属性的 fetch()):request_cf_overrides_cache_rules
  • 对于 Cache APIcaches.default.put() / caches.default.match()):cache_api_request_cf_overrides_cache_rules

必须启用这些标志以允许 Workers 脚本覆盖 Cache Rules。如果没有为您使用的 API 启用正确的标志,Worker 的缓存设置会被静默忽略,而是应用 Cache Rules。

兼容性日期行为

Worker 的兼容性日期决定哪些标志默认激活。当您设置兼容性日期时,启用日期在该日期或之前的所有标志会自动开启。

标志 默认启用 先决条件
request_cf_overrides_cache_rules (Fetch API) 兼容性日期在 2025-04-02 或之后
cache_api_compat_flags 兼容性日期在 2025-04-19 或之后
cache_api_request_cf_overrides_cache_rules (Cache API) 兼容性日期在 2025-05-19 或之后 需要 cache_api_compat_flags

Cache API 有额外要求:必须启用 cache_api_compat_flags,任何兼容性标志才能对 Cache API 生效。没有它,Cache API 忽略所有兼容性标志,即使您在配置中明确列出。

如果您的 Worker 使用上述日期之前的兼容性日期,必须手动将标志添加到配置中。否则,缓存行为遵循 Cache Rules 而非 Worker 的设置。

示例(较旧的兼容性日期)

Cache Rule 对 example.com/foo 绕过缓存。兼容性日期在 2025-04-02 之前的 Worker 通过 fetch() 设置 cacheEverything: true。由于兼容性日期太旧,request_cf_overrides_cache_rules 默认不激活,Cache Rule 获胜,响应不被缓存。

同样,如果您使用 Cache API 且兼容性日期在 2025-04-19 之前,cache_api_compat_flags 不激活。即使您手动将 cache_api_request_cf_overrides_cache_rules 添加到配置中,也没有效果,因为 Cache API 在没有 cache_api_compat_flags 的情况下不识别兼容性标志。

这篇文档对您有帮助吗?