Skip to content

Cache Rules - 缓存规则

Cloudflare Cache Rules 允许你精细控制哪些内容被缓存以及如何缓存。

Cache Rules vs Page Rules

特性Cache RulesPage Rules
功能专门的缓存控制综合性规则
性能更快执行较慢执行
优先级
配置界面现代化传统界面

建议优先使用 Cache Rules 处理缓存相关需求。

配置方式

通过 Dashboard

  1. 登录 Cloudflare Dashboard
  2. 选择域名 → Rules → Cache Rules
  3. 创建缓存规则

匹配条件

基本匹配

# 主机名
Hostname equals api.example.com

# 路径
Path starts with /api/
Path contains /images/
Path matches regex /*.jpg$

# 查询参数
URL query contains cache=false

高级匹配

# Cookie
Cookie contains session_id

# 请求头
Header Authorization contains Bearer

# 源站
Origin IP is 10.0.0.1

# SSL
SSL is not verified

缓存操作

1. 缓存级别

操作: Cache Level
选项:
  - Standard (标准) - 缓存静态资源
  - Simplified (简化) - 仅缓存 CSS/JS/Images
  - Aggressive (激进) - 缓存更多内容
  - Bypass (绕过) - 不缓存

2. 浏览器缓存 TTL

操作: Browser Cache TTL
选项:
  - Respect Existing Headers (遵循源站)
  - 0 minutes (不缓存)
  - 30 minutes
  - 1 hour
  - 1 day
  - 1 month
  - 1 year

3. 边缘缓存 TTL

操作: Edge Cache TTL
选项:
  - Respect Existing Headers
  - 1 hour
  - 1 day
  - 7 days
  - 30 days

4. 缓存键

操作: Cache Key
选项:
  - Default (默认) - 包含完整 URL
  - Ignore Query String (忽略查询参数)
  - Custom (自定义)

5. 绕过缓存

操作: Bypass Cache
选项:
  - On (绕过缓存)
  - Off (不绕过)

6. 缓存状态

操作: Cache Status
选项:
  - Bypass (不缓存)
  - Elidable (可缓存)

常用场景

场景 1: API 不缓存

名称: Bypass API Cache
条件:
  - Path starts with /api/

操作:
  - Cache Level = Bypass
  - Browser Cache TTL = 0 minutes

场景 2: 静态资源长缓存

名称: Cache Static Assets
条件:
  - Path matches regex /*.(css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2)$

操作:
  - Cache Level = Cache Everything
  - Edge Cache TTL = 1 month
  - Browser Cache TTL = 1 year

场景 3: 忽略查询参数缓存

名称: Ignore Query Params
条件:
  - Path starts with /images/

操作:
  - Cache Key = Ignore Query String
  - Edge Cache TTL = 7 days

场景 4: 管理后台不缓存

名称: Bypass Admin
条件:
  - Path starts with /admin/
  - Cookie contains admin_session

操作:
  - Cache Level = Bypass
  - Bypass Cache = On

场景 5: 带版本的静态文件

名称: Versioned Assets
条件:
  - Path matches regex /assets/.*-[a-f0-9]{8,}\.(css|js)$

操作:
  - Edge Cache TTL = 1 year
  - Browser Cache TTL = 1 year

场景 6: API 响应缓存

名称: Cache API Responses
条件:
  - Path starts with /api/v1/
  - Header CF-Cache-Status equals HIT

操作:
  - Edge Cache TTL = 5 minutes
  - Cache Level = Standard

缓存键自定义

Cache Key 配置

操作: Custom Cache Key

包含:
  - Hostname (主机名)
  - Path (路径)
  - Query String (查询参数)
  - Headers (请求头)
  - Cookies

排除:
  - 特定查询参数: utm_*, ref
  - 特定 Cookie: session_id

示例:忽略 UTM 参数

名称: Ignore UTM Params
条件:
  - URL query contains utm_source

操作:
  - Cache Key = Custom
  - Query String: Exclude utm_*

缓存清除

清除方式

# 1. 单个文件
Dashboard → Caching → Configuration → Purge Individual File

# 2. 通配符清除
*.css
/images/*

# 3. 清除所有缓存
Purge Everything

# 4. API 清除
curl -X POST "https://api.cloudflare.com/client/v4/zones/:zone_id/purge_cache" \
  -H "Authorization: Bearer :token" \
  -d '{"files":["https://example.com/style.css"]}'

通过 API 清除

javascript
// 清除单个 URL
await fetch('https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    files: ['https://example.com/style.css']
  })
})

// 清除多个 URL
await fetch('https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    files: [
      'https://example.com/style.css',
      'https://example.com/app.js'
    ]
  })
})

// 清除所有缓存
await fetch('https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    purge_everything: true
  })
})

// 按标签清除
await fetch('https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    tags: ['tag1', 'tag2']
  })
})

缓存标签 (Cache Tags)

设置缓存标签

javascript
// 通过响应头设置
// 源站响应中添加
CF-Cache-Tag: product-page,category-123

// 多个标签
CF-Cache-Tag: homepage,version-2

按标签清除

javascript
// 清除特定标签的缓存
await fetch('https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer API_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    tags: ['product-page']
  })
})

缓存响应头

源端响应头

# 控制 Cloudflare 缓存
Cache-Control: public, max-age=3600
Cache-Control: no-cache, no-store
Cache-Control: private

# 缓存验证
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT

Cloudflare 添加的响应头

# 缓存状态
CF-Cache-Status: HIT    # 缓存命中
CF-Cache-Status: MISS   # 未命中
CF-Cache-Status: EXPIRED# 已过期
CF-Cache-Status: BYPASS # 绕过缓存

# 缓存键
CF-Cache-Key: https://example.com/style.css

# Ray ID (请求标识)
CF-Ray: 1234567890abcde-KIX

最佳实践

1. 分层缓存策略

# HTML - 短缓存
Path: *.html
Edge Cache TTL: 1 hour
Browser Cache TTL: 0

# API - 不缓存
Path: /api/*
Cache Level: Bypass

# 静态资源 - 长缓存
Path: /*.(css|js|jpg|png)$
Edge Cache TTL: 1 month
Browser Cache TTL: 1 year

# 版本化资源 - 永久缓存
Path: /assets/*-[hash].*
Edge Cache TTL: 1 year
Browser Cache TTL: 1 year

2. 查询参数处理

# 忽略所有查询参数
Cache Key: Ignore Query String

# 仅忽略特定参数
Cache Key: Custom
Exclude: utm_source, utm_medium, utm_campaign

# 保留特定参数
Cache Key: Custom
Include: version, locale

3. 移动端分离

# 移动端单独缓存
条件:
  - User Agent contains Mobile

操作:
  - Cache Key: Custom (包含 UA)
  - Edge Cache TTL: 1 hour

4. 地理缓存

# 按地区缓存
条件:
  - Country CN

操作:
  - Cache Key: Custom (包含国家)
  - Edge Cache TTL: 1 day

调试缓存

检查缓存状态

bash
# 查看响应头
curl -I https://example.com/style.css

# 输出示例
CF-Cache-Status: HIT
CF-Ray: 1234567890abcde-KIX
Age: 3600
Cache-Control: public, max-age=31536000

强制刷新

bash
# 绕过缓存
curl -H "Pragma: no-cache" https://example.com/

# 使用 Cache-Control
curl -H "Cache-Control: no-cache" https://example.com/

常见问题

问题原因解决方案
内容未更新缓存未清除手动清除缓存
动态内容被缓存规则配置错误添加绕过规则
静态资源不缓存源端响应头设置 Cache-Control: public
API 返回旧数据错误缓存 API添加 /api/* 绕过规则

基于 MIT 许可证发布。