Cloudflare 缓存规则配置与命中验证
2026/6/5大约 2 分钟
Cloudflare 缓存规则配置与命中验证
博客域名通过 Cloudflare 代理访问,源站是 GitHub Pages。为了提升静态资源访问速度、减少重复回源,在 Cloudflare Dashboard 中配置了一条 Cache Rule,优先缓存构建产物、图片、图标和字体等静态资源。
配置位置
Cloudflare Dashboard 路径:
域名 -> Caching -> Cache Rules规则设计思路
本次目标不是缓存整站 HTML,而是优先缓存 CSS、JS、图片、favicon 这类长期稳定资源。VuePress 构建出的 assets 通常带 hash,适合较长 Edge TTL。HTML 页面暂不缓存,避免更新后被错误缓存的风险。
最终规则
匹配条件:
(http.host eq "blog.example.com" and
(starts_with(http.request.uri.path, "/assets/") or
ends_with(http.request.uri.path, ".css") or
ends_with(http.request.uri.path, ".js") or
ends_with(http.request.uri.path, ".mjs") or
ends_with(http.request.uri.path, ".png") or
ends_with(http.request.uri.path, ".jpg") or
ends_with(http.request.uri.path, ".jpeg") or
ends_with(http.request.uri.path, ".gif") or
ends_with(http.request.uri.path, ".webp") or
ends_with(http.request.uri.path, ".svg") or
ends_with(http.request.uri.path, ".ico") or
ends_with(http.request.uri.path, ".woff") or
ends_with(http.request.uri.path, ".woff2") or
ends_with(http.request.uri.path, ".ttf") or
ends_with(http.request.uri.path, ".otf")))规则动作:
Eligible for cache
Edge TTL: Ignore cache-control header and use this TTL
TTL: 1 monthBrowser TTL 暂不单独覆盖,避免前端资源更新后浏览器缓存过久导致排查困难。
遇到的问题:matches 正则不可用
最初使用了正则表达式:
http.request.uri.path matches "^/(assets/|.*\\.(css|js|mjs|png|jpg|jpeg|gif|webp|svg|ico|woff2?|ttf|otf)$)"Deploy 时报错:
not entitled: the use of operator Matches is not allowed,
a Business plan or a WAF Advanced plan is requiredCloudflare Free 计划不支持 matches 正则操作符。解决方式是把正则拆成 starts_with 和 ends_with 的组合,Free 计划完全可用。
验证方式
用响应头确认是否命中缓存:
curl -I https://blog.example.com/favicon.ico第一次请求:
cf-cache-status: REVALIDATED第二次请求:
cf-cache-status: HIT
age: 9HIT 表示命中 Cloudflare 边缘缓存,age 是缓存对象在边缘节点的存活秒数。
查看缓存命中率
在 Cloudflare Dashboard 查看整体数据:
域名 -> Caching -> Overview重点看:
- Cache Analytics
- Cache hit ratio
- Requests by cache status
- Bandwidth saved
按域名过滤流量:
域名 -> Analytics -> HTTP Traffic -> 按 hostname 过滤后续建议
当前规则可长期保留。如果以后要缓存 HTML,需要额外考虑:
- 首页和文章页更新后的刷新延迟
- GitHub Actions 部署后是否自动 Purge Cloudflare Cache
- 是否需要针对
text/html设置较短 TTL
当前阶段建议先保持静态资源缓存,不缓存 HTML。
