cloudflare-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare API
Cloudflare API
Hit the Cloudflare REST API directly when wrangler CLI or MCP servers aren't the right tool. For bulk operations, fleet-wide changes, and features that wrangler doesn't expose.
当wrangler CLI或MCP服务器不是合适工具时,直接调用Cloudflare REST API。适用于批量操作、全集群变更以及wrangler未暴露的功能。
When to Use This Instead of Wrangler or MCP
何时使用本技能而非Wrangler或MCP
| Use case | Wrangler | MCP | This skill |
|---|---|---|---|
| Deploy a Worker | Yes | Yes | No |
| Create a D1 database | Yes | Yes | No |
| Bulk update 50 DNS records | Slow (one at a time) | Slow (one tool call each) | Yes — batch script |
| Custom hostnames for white-label | No | Partial | Yes |
| Email routing rules | No | Partial | Yes |
| WAF/firewall rules | No | Yes but verbose | Yes — direct API |
| Redirect rules in bulk | No | One at a time | Yes — batch script |
| Zone settings across 20 zones | No | 20 separate calls | Yes — fleet script |
| Cache purge by tag/prefix | No | Yes | Yes (when scripting) |
| Worker route management | Limited | Yes | Yes (when bulk) |
| Analytics/logs query | No | Partial | Yes — GraphQL |
| D1 query/export across databases | One DB at a time | One DB at a time | Yes — cross-DB scripts |
| R2 bulk object operations | No | One at a time | Yes — S3 API + batch |
| KV bulk read/write/delete | One at a time | One at a time | Yes — bulk endpoints |
| Vectorize query/delete | No | Via Worker only | Yes — direct API |
| Queue message injection | No | Via Worker only | Yes — direct API |
| Audit all resources in account | No | Tedious | Yes — inventory script |
Rule of thumb: Single operations → MCP or wrangler. Bulk/fleet/scripted → API directly.
| 使用场景 | Wrangler | MCP | 本技能 |
|---|---|---|---|
| 部署Worker | 是 | 是 | 否 |
| 创建D1数据库 | 是 | 是 | 否 |
| 批量更新50条DNS记录 | 缓慢(逐条操作) | 缓慢(每次调用一个工具) | 是 — 批处理脚本 |
| 白标自定义主机名 | 否 | 部分支持 | 是 |
| 邮件路由规则 | 否 | 部分支持 | 是 |
| WAF/防火墙规则 | 否 | 支持但繁琐 | 是 — 直接调用API |
| 批量重定向规则 | 否 | 逐条操作 | 是 — 批处理脚本 |
| 20个Zone的配置设置 | 否 | 20次单独调用 | 是 — 全集群脚本 |
| 按标签/前缀清除缓存 | 否 | 是 | 是(脚本化操作时) |
| Worker路由管理 | 有限支持 | 是 | 是(批量操作时) |
| 分析/日志查询 | 否 | 部分支持 | 是 — GraphQL |
| 跨数据库的D1查询/导出 | 单库操作 | 单库操作 | 是 — 跨库脚本 |
| R2批量对象操作 | 否 | 逐条操作 | 是 — S3 API + 批处理 |
| KV批量读/写/删除 | 逐条操作 | 逐条操作 | 是 — 批量端点 |
| Vectorize查询/删除 | 否 | 仅通过Worker支持 | 是 — 直接调用API |
| 队列消息注入 | 否 | 仅通过Worker支持 | 是 — 直接调用API |
| 审计账户内所有资源 | 否 | 繁琐 | 是 — 清单脚本 |
经验法则:单次操作 → 使用MCP或wrangler。批量/全集群/脚本化操作 → 直接调用API。
Auth Setup
认证设置
API Token (recommended)
API令牌(推荐)
Create a scoped token at: Dashboard → My Profile → API Tokens → Create Token
bash
undefined在以下位置创建带权限范围的令牌:控制台 → 我的资料 → API令牌 → 创建令牌
bash
undefinedStore it
存储令牌
export CLOUDFLARE_API_TOKEN="your-token-here"
export CLOUDFLARE_API_TOKEN="your-token-here"
Test it
测试令牌
curl -s "https://api.cloudflare.com/client/v4/user/tokens/verify"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.success'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.success'
**Token scopes**: Always use minimal permissions. Common presets:
- "Edit zone DNS" — for DNS operations
- "Edit zone settings" — for zone config changes
- "Edit Cloudflare Workers" — for Worker route management
- "Read analytics" — for GraphQL analyticscurl -s "https://api.cloudflare.com/client/v4/user/tokens/verify"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.success'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.success'
**令牌权限范围**:始终使用最小权限。常见预设:
- "Edit zone DNS" — 用于DNS操作
- "Edit zone settings" — 用于Zone配置变更
- "Edit Cloudflare Workers" — 用于Worker路由管理
- "Read analytics" — 用于GraphQL分析Account and Zone IDs
账户与Zone ID
bash
undefinedbash
undefinedList your zones (find zone IDs)
列出所有Zone(查找Zone ID)
curl -s "https://api.cloudflare.com/client/v4/zones?per_page=50"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, id}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, id}'
curl -s "https://api.cloudflare.com/client/v4/zones?per_page=50"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, id}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, id}'
Get zone ID by domain name
通过域名获取Zone ID
ZONE_ID=$(curl -s "https://api.cloudflare.com/client/v4/zones?name=example.com"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[0].id')
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[0].id')
Store IDs in environment or a config file — don't hardcode them in scripts.ZONE_ID=$(curl -s "https://api.cloudflare.com/client/v4/zones?name=example.com"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[0].id')
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[0].id')
将ID存储在环境变量或配置文件中 — 不要在脚本中硬编码。Workflows
工作流
Bulk DNS Operations
批量DNS操作
Add/update many records at once (e.g. migrating a domain, setting up a new client):
bash
undefined批量添加/更新记录(例如迁移域名、设置新客户端):
bash
undefinedPattern: read records from a file, create in batch
模式:从文件读取记录,批量创建
while IFS=',' read -r type name content proxied; do
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"type":"$type","name":"$name","content":"$content","proxied":$proxied,"ttl":1}"
| jq '{name: .result.name, id: .result.id, success: .success}' sleep 0.25 # Rate limit: 1200 req/5min done < dns-records.csv
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"type":"$type","name":"$name","content":"$content","proxied":$proxied,"ttl":1}"
| jq '{name: .result.name, id: .result.id, success: .success}' sleep 0.25 # Rate limit: 1200 req/5min done < dns-records.csv
**Export all records from a zone** (backup or migration):
```bash
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=100" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
| jq -r '.result[] | [.type, .name, .content, .proxied] | @csv' > dns-export.csvFind and replace across records (e.g. IP migration):
bash
OLD_IP="203.0.113.1"
NEW_IP="198.51.100.1"while IFS=',' read -r type name content proxied; do
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"type":"$type","name":"$name","content":"$content","proxied":$proxied,"ttl":1}"
| jq '{name: .result.name, id: .result.id, success: .success}' sleep 0.25 # 速率限制:1200请求/5分钟 done < dns-records.csv
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"type":"$type","name":"$name","content":"$content","proxied":$proxied,"ttl":1}"
| jq '{name: .result.name, id: .result.id, success: .success}' sleep 0.25 # 速率限制:1200请求/5分钟 done < dns-records.csv
**导出Zone的所有记录**(备份或迁移):
```bash
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=100" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
| jq -r '.result[] | [.type, .name, .content, .proxied] | @csv' > dns-export.csv查找并替换记录(例如IP迁移):
bash
OLD_IP="203.0.113.1"
NEW_IP="198.51.100.1"Find records pointing to old IP
查找指向旧IP的记录
RECORDS=$(curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?content=$OLD_IP"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
RECORDS=$(curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?content=$OLD_IP"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
Update each one
更新每条记录
for RECORD_ID in $RECORDS; do
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"content":"$NEW_IP"}" | jq '.success' done
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"content":"$NEW_IP"}" | jq '.success' done
undefinedfor RECORD_ID in $RECORDS; do
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"content":"$NEW_IP"}" | jq '.success' done
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "{"content":"$NEW_IP"}" | jq '.success' done
undefinedCustom Hostnames (White-Label Client Domains)
自定义主机名(白标客户端域名)
For SaaS apps where clients use their own domain (e.g. → your Worker):
app.clientdomain.combash
undefined适用于SaaS应用中客户端使用自有域名的场景(例如 → 你的Worker):
app.clientdomain.combash
undefinedCreate custom hostname
创建自定义主机名
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_hostnames"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "hostname": "app.clientdomain.com", "ssl": { "method": "http", "type": "dv", "settings": { "min_tls_version": "1.2" } } }' | jq '{id: .result.id, status: .result.status, ssl_status: .result.ssl.status}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "hostname": "app.clientdomain.com", "ssl": { "method": "http", "type": "dv", "settings": { "min_tls_version": "1.2" } } }' | jq '{id: .result.id, status: .result.status, ssl_status: .result.ssl.status}'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_hostnames"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "hostname": "app.clientdomain.com", "ssl": { "method": "http", "type": "dv", "settings": { "min_tls_version": "1.2" } } }' | jq '{id: .result.id, status: .result.status, ssl_status: .result.ssl.status}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "hostname": "app.clientdomain.com", "ssl": { "method": "http", "type": "dv", "settings": { "min_tls_version": "1.2" } } }' | jq '{id: .result.id, status: .result.status, ssl_status: .result.ssl.status}'
List custom hostnames
列出自定义主机名
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_hostnames?per_page=50"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
| jq '.result[] | {hostname, status, ssl_status: .ssl.status}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
| jq '.result[] | {hostname, status, ssl_status: .ssl.status}'
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_hostnames?per_page=50"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
| jq '.result[] | {hostname, status, ssl_status: .ssl.status}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
| jq '.result[] | {hostname, status, ssl_status: .ssl.status}'
Check status (client needs to add CNAME)
检查状态(客户端需要添加CNAME)
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_hostnames/$HOSTNAME_ID"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result.status'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result.status'
**Client setup**: They add a CNAME: `app.clientdomain.com → your-worker.your-domain.com`curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_hostnames/$HOSTNAME_ID"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result.status'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result.status'
**客户端设置**:他们需要添加CNAME记录:`app.clientdomain.com → your-worker.your-domain.com`Email Routing Rules
邮件路由规则
bash
undefinedbash
undefinedEnable email routing on zone
在Zone上启用邮件路由
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/enable"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/enable"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
Create a routing rule (forward info@ to a real address)
创建路由规则(将info@转发到真实邮箱)
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/rules"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Forward info@", "enabled": true, "matchers": [{"type": "literal", "field": "to", "value": "info@example.com"}], "actions": [{"type": "forward", "value": ["real-inbox@gmail.com"]}] }' | jq '.success'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Forward info@", "enabled": true, "matchers": [{"type": "literal", "field": "to", "value": "info@example.com"}], "actions": [{"type": "forward", "value": ["real-inbox@gmail.com"]}] }' | jq '.success'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/rules"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Forward info@", "enabled": true, "matchers": [{"type": "literal", "field": "to", "value": "info@example.com"}], "actions": [{"type": "forward", "value": ["real-inbox@gmail.com"]}] }' | jq '.success'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Forward info@", "enabled": true, "matchers": [{"type": "literal", "field": "to", "value": "info@example.com"}], "actions": [{"type": "forward", "value": ["real-inbox@gmail.com"]}] }' | jq '.success'
Create catch-all rule
创建 catch-all 规则
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/rules"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Catch-all", "enabled": true, "matchers": [{"type": "all"}], "actions": [{"type": "forward", "value": ["catchall@company.com"]}] }' | jq '.success'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Catch-all", "enabled": true, "matchers": [{"type": "all"}], "actions": [{"type": "forward", "value": ["catchall@company.com"]}] }' | jq '.success'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/rules"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Catch-all", "enabled": true, "matchers": [{"type": "all"}], "actions": [{"type": "forward", "value": ["catchall@company.com"]}] }' | jq '.success'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "name": "Catch-all", "enabled": true, "matchers": [{"type": "all"}], "actions": [{"type": "forward", "value": ["catchall@company.com"]}] }' | jq '.success'
List rules
列出规则
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/rules"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, enabled, matchers, actions}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, enabled, matchers, actions}'
undefinedcurl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/email/routing/rules"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, enabled, matchers, actions}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {name, enabled, matchers, actions}'
undefinedCache Purge
缓存清除
bash
undefinedbash
undefinedPurge everything (nuclear option)
清除所有缓存(终极选项)
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"purge_everything": true}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"purge_everything": true}'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"purge_everything": true}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"purge_everything": true}'
Purge specific URLs
清除指定URL的缓存
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"files": ["https://example.com/styles.css", "https://example.com/app.js"]}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"files": ["https://example.com/styles.css", "https://example.com/app.js"]}'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"files": ["https://example.com/styles.css", "https://example.com/app.js"]}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"files": ["https://example.com/styles.css", "https://example.com/app.js"]}'
Purge by cache tag (requires Enterprise or cache tag headers)
按缓存标签清除(需要企业版或缓存标签头)
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"tags": ["product-123", "homepage"]}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"tags": ["product-123", "homepage"]}'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"tags": ["product-123", "homepage"]}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"tags": ["product-123", "homepage"]}'
Purge by prefix
按前缀清除
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"prefixes": ["https://example.com/images/"]}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"prefixes": ["https://example.com/images/"]}'
undefinedcurl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"prefixes": ["https://example.com/images/"]}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"prefixes": ["https://example.com/images/"]}'
undefinedRedirect Rules (Bulk)
重定向规则(批量)
bash
undefinedbash
undefinedCreate a redirect rule
创建重定向规则
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_dynamic_redirect/entrypoint"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [ { "expression": "(http.request.uri.path eq "/old-page")", "description": "Redirect old-page to new-page", "action": "redirect", "action_parameters": { "from_value": { "target_url": {"value": "https://example.com/new-page"}, "status_code": 301 } } } ] }'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [ { "expression": "(http.request.uri.path eq "/old-page")", "description": "Redirect old-page to new-page", "action": "redirect", "action_parameters": { "from_value": { "target_url": {"value": "https://example.com/new-page"}, "status_code": 301 } } } ] }'
**For bulk redirects** (301s from a CSV), generate the rules array programmatically:
```python
import json, csv
rules = []
with open('redirects.csv') as f:
for row in csv.reader(f):
old_path, new_url = row
rules.append({
"expression": f'(http.request.uri.path eq "{old_path}")',
"description": f"Redirect {old_path}",
"action": "redirect",
"action_parameters": {
"from_value": {
"target_url": {"value": new_url},
"status_code": 301
}
}
})
print(json.dumps({"rules": rules}, indent=2))curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_dynamic_redirect/entrypoint"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [ { "expression": "(http.request.uri.path eq "/old-page")", "description": "Redirect old-page to new-page", "action": "redirect", "action_parameters": { "from_value": { "target_url": {"value": "https://example.com/new-page"}, "status_code": 301 } } } ] }'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [ { "expression": "(http.request.uri.path eq "/old-page")", "description": "Redirect old-page to new-page", "action": "redirect", "action_parameters": { "from_value": { "target_url": {"value": "https://example.com/new-page"}, "status_code": 301 } } } ] }'
**批量重定向**(从CSV文件生成301重定向):程序化生成规则数组:
```python
import json, csv
rules = []
with open('redirects.csv') as f:
for row in csv.reader(f):
old_path, new_url = row
rules.append({
"expression": f'(http.request.uri.path eq "{old_path}")',
"description": f"Redirect {old_path}",
"action": "redirect",
"action_parameters": {
"from_value": {
"target_url": {"value": new_url},
"status_code": 301
}
}
})
print(json.dumps({"rules": rules}, indent=2))Zone Settings (Fleet-Wide)
Zone设置(全集群)
Apply the same settings across multiple zones:
bash
undefined在多个Zone上应用相同设置:
bash
undefinedSettings to apply
要应用的设置
SETTINGS='{"value":"full"}' # SSL mode: full (strict)
SETTINGS='{"value":"full"}' # SSL模式:full(严格)
Get all active zones
获取所有活跃Zone
ZONES=$(curl -s "https://api.cloudflare.com/client/v4/zones?status=active&per_page=50"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
ZONES=$(curl -s "https://api.cloudflare.com/client/v4/zones?status=active&per_page=50"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[].id')
Apply to each zone
应用到每个Zone
for ZONE in $ZONES; do
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE/settings/ssl"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "$SETTINGS" | jq "{zone: .result.id, success: .success}" sleep 0.25 done
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "$SETTINGS" | jq "{zone: .result.id, success: .success}" sleep 0.25 done
Common fleet settings:
- `ssl` — "full" or "strict"
- `min_tls_version` — "1.2"
- `always_use_https` — "on"
- `security_level` — "medium"
- `browser_cache_ttl` — 14400for ZONE in $ZONES; do
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE/settings/ssl"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "$SETTINGS" | jq "{zone: .result.id, success: .success}" sleep 0.25 done
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d "$SETTINGS" | jq "{zone: .result.id, success: .success}" sleep 0.25 done
常见全集群设置:
- `ssl` — "full" 或 "strict"
- `min_tls_version` — "1.2"
- `always_use_https` — "on"
- `security_level` — "medium"
- `browser_cache_ttl` — 14400WAF / Firewall Rules
WAF / 防火墙规则
bash
undefinedbash
undefinedCreate a WAF custom rule (block by country)
创建WAF自定义规则(按国家拦截)
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_firewall_custom/entrypoint"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(ip.geoip.country in {"RU" "CN"})", "action": "block", "description": "Block traffic from RU and CN" }] }'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(ip.geoip.country in {"RU" "CN"})", "action": "block", "description": "Block traffic from RU and CN" }] }'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_firewall_custom/entrypoint"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(ip.geoip.country in {"RU" "CN"})", "action": "block", "description": "Block traffic from RU and CN" }] }'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(ip.geoip.country in {"RU" "CN"})", "action": "block", "description": "Block traffic from RU and CN" }] }'
Rate limiting rule
速率限制规则
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_ratelimit/entrypoint"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(http.request.uri.path contains "/api/")", "action": "block", "ratelimit": { "characteristics": ["ip.src"], "period": 60, "requests_per_period": 100 }, "description": "Rate limit API to 100 req/min per IP" }] }'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(http.request.uri.path contains "/api/")", "action": "block", "ratelimit": { "characteristics": ["ip.src"], "period": 60, "requests_per_period": 100 }, "description": "Rate limit API to 100 req/min per IP" }] }'
undefinedcurl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_ratelimit/entrypoint"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(http.request.uri.path contains "/api/")", "action": "block", "ratelimit": { "characteristics": ["ip.src"], "period": 60, "requests_per_period": 100 }, "description": "Rate limit API to 100 req/min per IP" }] }'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "rules": [{ "expression": "(http.request.uri.path contains "/api/")", "action": "block", "ratelimit": { "characteristics": ["ip.src"], "period": 60, "requests_per_period": 100 }, "description": "Rate limit API to 100 req/min per IP" }] }'
undefinedWorker Routes
Worker路由
bash
undefinedbash
undefinedList routes
列出路由
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/workers/routes"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {pattern, id}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {pattern, id}'
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/workers/routes"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {pattern, id}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq '.result[] | {pattern, id}'
Create route
创建路由
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/workers/routes"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"pattern": "api.example.com/*", "script": "my-worker"}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"pattern": "api.example.com/*", "script": "my-worker"}'
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/workers/routes"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"pattern": "api.example.com/*", "script": "my-worker"}'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{"pattern": "api.example.com/*", "script": "my-worker"}'
Delete route
删除路由
curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/workers/routes/$ROUTE_ID"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
undefinedcurl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/workers/routes/$ROUTE_ID"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
undefinedAnalytics (GraphQL)
分析(GraphQL)
bash
undefinedbash
undefinedWorker analytics (requests, errors, CPU time)
Worker分析(请求数、错误数、CPU时间)
curl -s -X POST "https://api.cloudflare.com/client/v4/graphql"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "query": "{ viewer { zones(filter: {zoneTag: "'$ZONE_ID'"}) { httpRequests1dGroups(limit: 7, filter: {date_gt: "2026-03-10"}) { dimensions { date } sum { requests pageViews } } } } }" }' | jq '.data.viewer.zones[0].httpRequests1dGroups'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "query": "{ viewer { zones(filter: {zoneTag: "'$ZONE_ID'"}) { httpRequests1dGroups(limit: 7, filter: {date_gt: "2026-03-10"}) { dimensions { date } sum { requests pageViews } } } } }" }' | jq '.data.viewer.zones[0].httpRequests1dGroups'
undefinedcurl -s -X POST "https://api.cloudflare.com/client/v4/graphql"
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "query": "{ viewer { zones(filter: {zoneTag: "'$ZONE_ID'"}) { httpRequests1dGroups(limit: 7, filter: {date_gt: "2026-03-10"}) { dimensions { date } sum { requests pageViews } } } } }" }' | jq '.data.viewer.zones[0].httpRequests1dGroups'
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
-H "Content-Type: application/json"
-d '{ "query": "{ viewer { zones(filter: {zoneTag: "'$ZONE_ID'"}) { httpRequests1dGroups(limit: 7, filter: {date_gt: "2026-03-10"}) { dimensions { date } sum { requests pageViews } } } } }" }' | jq '.data.viewer.zones[0].httpRequests1dGroups'
undefinedRate Limits
速率限制
| Endpoint | Limit |
|---|---|
| Most API calls | 1200 requests / 5 minutes |
| DNS record operations | 1200 / 5 min (shared with above) |
| Cache purge | 1000 purge calls / day |
| Zone creation | 5 per minute |
In scripts: Add between calls for sustained operations. Use or for controlled parallelism.
sleep 0.25p-limitxargs -P 4| 端点 | 限制 |
|---|---|
| 大多数API调用 | 1200请求/5分钟 |
| DNS记录操作 | 1200/5分钟(与上述共享) |
| 缓存清除 | 1000次清除调用/天 |
| Zone创建 | 5次/分钟 |
脚本中注意事项:持续操作时在调用之间添加。使用或进行可控并行处理。
sleep 0.25p-limitxargs -P 4Script Generation
脚本生成
When the user describes what they need, generate a script in that:
.jez/scripts/- Reads API token from environment (never hardcode)
- Handles pagination for list operations
- Includes error checking (after each call)
jq '.success' - Adds rate limit sleep between calls
- Logs what it does
- Supports where possible
--dry-run
Prefer + for simple operations. Use Python for complex logic (pagination loops, error handling, CSV processing). Use TypeScript with the npm package for type safety in larger scripts.
curljqcloudflare当用户描述需求时,在目录下生成脚本,要求:
.jez/scripts/- 从环境变量读取API令牌(绝不硬编码)
- 处理列表操作的分页
- 包含错误检查(每次调用后使用)
jq '.success' - 在调用之间添加速率限制等待
- 记录操作内容
- 尽可能支持模式
--dry-run
简单操作优先使用 + 。复杂逻辑(分页循环、错误处理、CSV处理)使用Python。大型脚本使用带 npm包的TypeScript以保证类型安全。
curljqcloudflareAPI Reference
API参考
Base URL:
https://api.cloudflare.com/client/v4/Full docs:
https://developers.cloudflare.com/api/The API follows a consistent pattern:
- — list
GET /zones - — create
POST /zones - — read
GET /zones/:id - — update
PATCH /zones/:id - — delete
DELETE /zones/:id - — update setting
PUT /zones/:id/settings/:name
Every response has .
{ success: bool, errors: [], messages: [], result: {} }基础URL:
https://api.cloudflare.com/client/v4/完整文档:
https://developers.cloudflare.com/api/API遵循一致的模式:
- — 列出
GET /zones - — 创建
POST /zones - — 读取
GET /zones/:id - — 更新
PATCH /zones/:id - — 删除
DELETE /zones/:id - — 更新设置
PUT /zones/:id/settings/:name
每个响应格式:。
{ success: bool, errors: [], messages: [], result: {} }Reference Files
参考文件
| When | Read |
|---|---|
| D1, R2, KV, Workers, Vectorize, Queues API patterns | references/developer-platform-api.md |
| 场景 | 阅读文档 |
|---|---|
| D1、R2、KV、Workers、Vectorize、Queues API模式 | references/developer-platform-api.md |