docs/docs/rules/cache.md
cache 协议用于快速设置响应的缓存控制头,帮助控制浏览器和服务器的缓存行为。可以为匹配的响应设置缓存策略,包括:
no-cache)no-store)这可以帮助优化网站性能或确保特定资源不会被缓存。
cache 支持多种方式设置缓存策略:
直接在规则中指定缓存策略。
# 设置缓存5秒,支持正整数、0、负整数
pattern cache://5 [lineProps...] [filters...]
# 设置缓存头:`cache-control: no-cache`、`pragma: no-cache`
# `no-cache` 可简写为 `no`
pattern cache://no-cache [lineProps...] [filters...]
# 设置缓存头:`cache-control: no-store`、`pragma: no-cache`
pattern cache://no-store [lineProps...] [filters...]
示例:
https://example.com/api/data cache://no-cache
https://example.com/static/js cache://86400 # 缓存24小时
当需要复用缓存策略或策略较复杂时可使用此方式。
pattern cache://{custom-key} [lineProps...] [filters...]
``` custom-key
no-cache
```
引用在界面 Values 中预先定义好的缓存策略。
pattern cache://{key-of-values} [lineProps...] [filters...]
前提: 在 Values 中存在一个名为 key-of-values 的键,其值为缓存策略。
当前不支持 从本地文件或远程 URL 动态加载缓存配置。
| 参数 | 是否必填 | 描述与示例 |
|---|---|---|
| pattern | 是 | 用于匹配请求 URL 的表达式。 |
| • 支持域名、路径、通配符、正则表达式。 | ||
| • 详见 匹配模式文档。 | ||
| value | 是 | 缓存策略值: |
• 数字:缓存秒数(如 60 表示缓存60秒) | ||
| • no-cache 或 no:允许缓存但每次需重新验证 | ||
| • no-store:完全禁止缓存 | ||
| • 支持内联、内嵌、Values 引用 | ||
| • ⚠️ 不支持从文件或远程 URL 加载 | ||
| lineProps | 否 | 为规则设置附加属性。 |
• 例如:lineProps://important 可提升此规则的优先级。 | ||
| • 详见 lineProps 文档。 | ||
| filters | 否 | 可选的过滤条件,用于精确控制规则生效的场景。 |
| • 可匹配请求的 URL、方法、头部、体内容。 | ||
| • 可匹配响应的状态码、头部。 | ||
| • 详见 过滤器文档。 |
影响的响应头:
Cache-ControlExpiresPragma| 策略 | 含义 | 典型使用场景 |
|---|---|---|
数字(如 60) | 设置资源缓存指定秒数 | 静态资源、不经常变化的API响应 |
| no-cache(或 no) | 允许缓存但每次使用前必须验证 | 经常变化的内容,如用户数据、实时报价 |
| no-store | 完全禁止缓存任何版本 | 敏感数据、支付页面、一次性令牌 |
# 静态资源缓存1小时
https://example.com/static cache://3600
# API接口禁用缓存
https://example.com/api cache://no-cache
# 敏感数据禁止缓存
https://example.com/account cache://no-store
https://example.com/reports cache://{report-cache-policy}
``` report-cache-policy
no-cache
```
仅对特定响应状态码设置缓存:
https://example.com/api cache://300 includeFilter://s:200
假设在 Values 中已有 static-cache 配置:
https://example.com/assets cache://{static-cache}
核心原理:cache 协议自动设置相应的缓存控制头:
cache://5 设置:
Cache-Control: max-age=5
Expires: [当前时间+5秒]
cache://no-cache 设置:
Cache-Control: no-cache
Pragma: no-cache
cache://no-store 设置:
Cache-Control: no-store
Pragma: no-cache
关联协议:
resHeaders 协议手动设置缓存头。no-cache 不代表"不缓存",而是"使用前必须验证"disable://cache 协议Delete Response Header):delete://resHeaders.xxxDelete Response Cookie):delete://resCookies.xxx