用好 Cloudflare:从带宽、源站到对象存储的省钱实战命令手册
Cloudflare 如何降低成本|附完整命令
在网站、SaaS、API 服务或跨境业务中,成本通常集中在四个地方:服务器带宽、源站算力、对象存储流量、安全防护费用以及运维时间成本。Cloudflare 的价值不只是“套一层 CDN”,更重要的是通过缓存、安全、边缘计算、隧道、对象存储等能力,把原本需要源站或第三方服务承担的工作前移到边缘节点,从而降低整体成本。
本文将从实战角度讲解:如何用 Cloudflare 降低成本,并附上可直接参考的完整命令,包括 DNS 接入、缓存优化、Cloudflare Tunnel、Workers、Pages、R2、Wrangler、API 自动化配置等内容。
一、Cloudflare 能降低哪些成本?
在正式操作之前,先明确 Cloudflare 能帮助我们降低的成本类型。
1. 降低服务器带宽成本
很多云服务器的出网带宽非常贵,尤其是海外云厂商、国内云厂商的公网流量包、按量计费带宽等。如果网站静态资源较多,例如:
- 图片;
- CSS;
- JavaScript;
- 字体文件;
- 视频封面;
- 下载文件;
- 文档页面;
- API 中可缓存的数据;
那么接入 Cloudflare 后,可以让大量请求命中 Cloudflare 边缘缓存,减少源站流量。
例如原来每天 500GB 出网流量,如果 Cloudflare 缓存命中率达到 80%,源站实际只需要承担 100GB 左右的流量,带宽成本会明显下降。
2. 降低源站服务器配置成本
Cloudflare 不仅缓存静态资源,也可以通过合理配置缓存 HTML、API 响应、重定向规则等方式减少源站压力。
源站压力下降后,原本需要:
- 4 核 8G;
- 8 核 16G;
- 多台负载均衡服务器;
可能可以降级为更低配置,甚至部分静态站点可以直接迁移到 Cloudflare Pages,不再需要传统服务器。
3. 降低安全防护成本
如果直接暴露源站,常见成本包括:
- DDoS 防护;
- WAF;
- CC 防护;
- Bot 过滤;
- IP 黑名单;
- TLS 证书管理;
- 安全规则维护。
Cloudflare 免费版就提供基础 DDoS 防护、SSL、DNS、访问规则等功能,Pro、Business、Enterprise 版本则提供更强大的 WAF 和 Bot 管理能力。对于很多中小网站来说,Cloudflare 可以替代一部分昂贵的安全防护服务。
4. 降低运维和部署成本
Cloudflare Pages、Workers、Tunnel、R2 等产品可以减少传统运维工作量,例如:
- 不需要手动部署静态站点;
- 不需要维护 Nginx 反向代理;
- 不需要暴露源站公网 IP;
- 不需要单独购买对象存储 CDN 回源流量;
- 不需要手动续签 SSL 证书;
- 不需要复杂的 CI/CD 服务器。
节省下来的不是一两美元,而是长期的运维人力成本。
二、总体优化思路
使用 Cloudflare 降低成本,可以按照下面的优先级进行:
- DNS 接入 Cloudflare;
- 开启代理模式,隐藏源站 IP;
- 配置 SSL/TLS,减少证书维护成本;
- 设置缓存规则,提高缓存命中率;
- 压缩和优化静态资源;
- 使用 Cloudflare Tunnel 替代公网暴露源站;
- 静态网站迁移到 Cloudflare Pages;
- 使用 Workers 处理轻量逻辑;
- 使用 R2 替代传统对象存储并减少出网费;
- 使用 API 或 Wrangler 自动化管理配置。
三、安装必要工具
本文主要会用到三个工具:
cloudflared:用于 Cloudflare Tunnel;wrangler:用于 Workers、Pages、R2 管理;curl:用于调用 Cloudflare API。
1. 安装 Node.js
Wrangler 需要 Node.js 环境。
Ubuntu / Debian:
sudo apt update
sudo apt install -y nodejs npm
node -v
npm -v
如果系统自带 Node.js 版本太旧,可以使用 NodeSource:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
node -v
npm -v
CentOS / Rocky Linux / AlmaLinux:
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo yum install -y nodejs
node -v
npm -v
macOS:
brew install node
node -v
npm -v
2. 安装 Wrangler
npm install -g wrangler
wrangler --version
登录 Cloudflare:
wrangler login
查看账户信息:
wrangler whoami
3. 安装 cloudflared
Ubuntu / Debian:
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared-linux-amd64.deb
cloudflared --version
CentOS / Rocky Linux:
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm
sudo rpm -i cloudflared-linux-x86_64.rpm
cloudflared --version
macOS:
brew install cloudflare/cloudflare/cloudflared
cloudflared --version
四、DNS 接入 Cloudflare
首先需要把域名托管到 Cloudflare DNS。
操作步骤
- 登录 Cloudflare;
- 添加站点;
- 输入域名;
- 选择套餐;
- Cloudflare 扫描现有 DNS;
- 修改域名注册商处的 NS 服务器;
- 等待生效。
如果你已经在 Cloudflare 中添加了域名,可以用 API 查看 Zone ID。
获取 Zone ID
先设置变量:
export CF_API_TOKEN="你的_Cloudflare_API_Token"
export CF_DOMAIN="example.com"
查询 Zone ID:
curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${CF_DOMAIN}" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json"
如果你想提取 Zone ID,可以使用 jq:
sudo apt install -y jq
然后执行:
export CF_ZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${CF_DOMAIN}" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" | jq -r '.result[0].id')
echo $CF_ZONE_ID
五、开启 Cloudflare 代理,隐藏源站 IP
Cloudflare DNS 中有两种状态:
- 灰色云朵:仅 DNS 解析;
- 橙色云朵:通过 Cloudflare 代理。
只有开启橙色云朵后,流量才会经过 Cloudflare,才能享受缓存、防护、隐藏源站 IP 等能力。
假设你的源站 IP 是 1.2.3.4,域名是 www.example.com。
创建 A 记录并开启代理
export CF_RECORD_NAME="www.example.com"
export CF_ORIGIN_IP="1.2.3.4"
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"type": "A",
"name": "'"${CF_RECORD_NAME}"'",
"content": "'"${CF_ORIGIN_IP}"'",
"ttl": 1,
"proxied": true
}'
查询 DNS 记录
curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" | jq
六、配置 SSL/TLS,减少证书维护成本
Cloudflare 支持多种 SSL 模式:
- Off:关闭;
- Flexible:浏览器到 Cloudflare 加密,Cloudflare 到源站不加密;
- Full:两段都加密,但不严格校验证书;
- Full Strict:两段都加密,严格校验证书。
推荐使用:
Full Strict
这样安全性更高。
使用 API 设置 SSL 模式为 Full Strict
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/ssl" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "strict"
}'
开启 Always Use HTTPS
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/always_use_https" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "on"
}'
开启自动 HTTPS 重写
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/automatic_https_rewrites" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "on"
}'
开启 TLS 1.3
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/tls_1_3" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "on"
}'
七、配置缓存策略,降低源站带宽
Cloudflare 降低成本的核心是缓存。缓存命中率越高,源站成本越低。
1. 源站添加缓存头
在 Nginx 中,可以给静态资源添加长期缓存头。
编辑 Nginx 配置:
sudo nano /etc/nginx/conf.d/example.conf
添加:
server {
listen 80;
server_name www.example.com;
root /var/www/example;
location ~* \.(jpg|jpeg|png|gif|webp|avif|svg|css|js|woff|woff2|ttf|eot|ico)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}
}
测试并重载:
sudo nginx -t
sudo systemctl reload nginx
2. 开启 Brotli 压缩
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/brotli" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "on"
}'
Brotli 可以压缩文本资源,例如 HTML、CSS、JavaScript、JSON,从而降低传输体积。
3. 开启 Auto Minify
压缩 HTML、CSS、JS:
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/minify" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": {
"css": "on",
"html": "on",
"js": "on"
}
}'
4. 设置浏览器缓存 TTL
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/browser_cache_ttl" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": 2592000
}'
这里的 2592000 表示 30 天。
5. 清理缓存
当你更新静态资源时,可以清理 Cloudflare 缓存。
清理全部缓存:
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/purge_cache" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"purge_everything": true
}'
清理指定 URL:
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/purge_cache" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"files": [
"https://www.example.com/css/app.css",
"https://www.example.com/js/app.js"
]
}'
八、使用 Cache Rules 缓存静态资源
Cloudflare 新版更推荐使用 Cache Rules,而不是旧版 Page Rules。下面是使用 API 创建规则的示例。
创建静态资源缓存规则
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/rulesets" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "Cache static assets",
"description": "Cache static assets for cost reduction",
"kind": "zone",
"phase": "http_request_cache_settings",
"rules": [
{
"action": "set_cache_settings",
"expression": "(http.request.uri.path matches \"^/.*\\.(jpg|jpeg|png|gif|webp|avif|svg|css|js|woff|woff2|ttf|ico)$\")",
"description": "Cache static files for 30 days",
"enabled": true,
"action_parameters": {
"cache": true,
"edge_ttl": {
"mode": "override_origin",
"default": 2592000
},
"browser_ttl": {
"mode": "override_origin",
"default": 2592000
}
}
}
]
}'
这条规则会让常见静态资源在 Cloudflare 边缘缓存 30 天,从而降低源站回源请求。
九、缓存 HTML 页面,进一步降低成本
对于博客、文档站、官网、新闻站等页面,如果页面内容不是实时变化,可以考虑缓存 HTML。
例如:
- WordPress 文章页;
- Hexo / Hugo / VitePress / Docusaurus 页面;
- 产品介绍页;
- 帮助中心;
- 营销落地页。
创建 HTML 缓存规则
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/rulesets" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "Cache HTML pages",
"description": "Cache anonymous HTML pages",
"kind": "zone",
"phase": "http_request_cache_settings",
"rules": [
{
"action": "set_cache_settings",
"expression": "(http.request.method eq \"GET\" and http.request.uri.path ne \"/admin\" and not starts_with(http.request.uri.path, \"/api\") and not http.cookie contains \"session\")",
"description": "Cache normal HTML pages for 10 minutes",
"enabled": true,
"action_parameters": {
"cache": true,
"edge_ttl": {
"mode": "override_origin",
"default": 600
},
"browser_ttl": {
"mode": "override_origin",
"default": 300
}
}
}
]
}'
注意:如果网站有登录态、购物车、用户中心,一定不要盲目缓存所有 HTML,否则可能出现用户数据串页等严重问题。
十、使用 Cloudflare Tunnel 隐藏源站并减少安全成本
Cloudflare Tunnel 可以让源站不暴露公网 IP。它的作用是让服务器主动连接 Cloudflare,由 Cloudflare 将请求转发到内网服务。
这有几个好处:
- 源站无需开放公网端口;
- 降低被扫描、攻击的概率;
- 不需要复杂的安全组白名单;
- 可以把内网服务安全暴露到公网;
- 可以减少防火墙和反向代理维护成本。
1. 登录 cloudflared
cloudflared tunnel login
执行后会打开浏览器,选择对应域名授权。
2. 创建 Tunnel
cloudflared tunnel create example-tunnel
查看 Tunnel 列表:
cloudflared tunnel list
3. 创建 Tunnel 配置文件
创建目录:
mkdir -p ~/.cloudflared
编辑配置文件:
nano ~/.cloudflared/config.yml
写入以下内容:
tunnel: example-tunnel
credentials-file: /root/.cloudflared/你的-tunnel-id.json
ingress:
- hostname: www.example.com
service: http://localhost:80
- hostname: api.example.com
service: http://localhost:3000
- service: http_status:404
如果你的配置文件在普通用户目录,需要把 /root/.cloudflared/ 改为实际路径。
4. 绑定域名
cloudflared tunnel route dns example-tunnel www.example.com
cloudflared tunnel route dns example-tunnel api.example.com
5. 测试运行
cloudflared tunnel run example-tunnel
如果访问正常,可以安装为系统服务。
6. 安装为 systemd 服务
sudo cloudflared service install
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
sudo systemctl status cloudflared
查看日志:
journalctl -u cloudflared -f
十一、使用 Cloudflare Pages 替代静态服务器
如果你的网站是静态站点,例如:
- Hugo;
- Hexo;
- Astro;
- VitePress;
- Docusaurus;
- Vue / React 构建后的静态页面;
- 纯 HTML 网站;
可以直接部署到 Cloudflare Pages。这样可以省掉一台服务器,减少运维和带宽成本。
1. 使用 Wrangler 创建 Pages 项目
先进入你的项目目录:
cd my-site
安装依赖并构建:
npm install
npm run build
假设构建目录是 dist,创建 Pages 项目:
wrangler pages project create my-site
部署:
wrangler pages deploy dist --project-name=my-site
2. Vue / Vite 项目部署示例
npm create vite@latest my-vite-site
cd my-vite-site
npm install
npm run build
wrangler pages project create my-vite-site
wrangler pages deploy dist --project-name=my-vite-site
3. Hugo 项目部署示例
安装 Hugo:
sudo apt install -y hugo
创建站点:
hugo new site my-hugo-site
cd my-hugo-site
git init
hugo
wrangler pages project create my-hugo-site
wrangler pages deploy public --project-name=my-hugo-site
十二、使用 Workers 承担轻量逻辑,减少源站压力
Cloudflare Workers 可以在边缘节点运行 JavaScript / TypeScript 代码。它适合处理:
- 重定向;
- A/B 测试;
- 简单 API;
- 鉴权前置;
- 缓存控制;
- Header 修改;
- 图片代理;
- 轻量聚合请求。
如果某些请求无需回源,Workers 可以直接返回结果,从而减少源站压力。
1. 创建 Workers 项目
mkdir cf-worker-cost-demo
cd cf-worker-cost-demo
npm init -y
npm install -D wrangler
创建 wrangler.toml:
nano wrangler.toml
写入:
name = "cf-worker-cost-demo"
main = "src/index.js"
compatibility_date = "2024-09-01"
创建代码目录:
mkdir -p src
nano src/index.js
写入一个简单的缓存 Worker:
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (url.pathname === "/health") {
return new Response("ok", {
headers: {
"Content-Type": "text/plain"
}
});
}
const cache = caches.default;
const cacheKey = new Request(url.toString(), request);
let response = await cache.match(cacheKey);
if (!response) {
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set("Cache-Control", "public, max-age=300");
ctx.waitUntil(cache.put(cacheKey, response.clone()));
}
return response;
}
};
部署:
npx wrangler deploy
2. 绑定自定义域名路由
如果你要让 Worker 处理某个路径,例如:
https://www.example.com/api-cache/*
可以在 Cloudflare 控制台配置,也可以在 wrangler.toml 中配置路由:
name = "cf-worker-cost-demo"
main = "src/index.js"
compatibility_date = "2024-09-01"
routes = [
{ pattern = "www.example.com/api-cache/*", zone_name = "example.com" }
]
然后重新部署:
npx wrangler deploy
十三、使用 R2 降低对象存储出网成本
Cloudflare R2 是对象存储,兼容 S3 API。它最大的特点之一是:没有传统意义上的出口流量费用。对于图片、附件、下载资源、备份文件等场景,R2 可以明显降低对象存储成本。
适合迁移到 R2 的内容包括:
- 用户上传图片;
- 文档附件;
- 软件安装包;
- 静态资源;
- 备份文件;
- 博客图床;
- 公共下载文件。
1. 创建 R2 Bucket
wrangler r2 bucket create my-assets
查看 Bucket:
wrangler r2 bucket list
2. 上传文件到 R2
echo "hello cloudflare r2" > hello.txt
wrangler r2 object put my-assets/hello.txt --file=hello.txt
查看对象:
wrangler r2 object get my-assets/hello.txt
删除对象:
wrangler r2 object delete my-assets/hello.txt
3. 使用 rclone 管理 R2
安装 rclone:
curl https://rclone.org/install.sh | sudo bash
rclone version
配置 R2:
rclone config
配置时选择:
n) New remote
name> cloudflare-r2
Storage> s3
provider> Cloudflare
access_key_id> 你的_R2_Access_Key_ID
secret_access_key> 你的_R2_Secret_Access_Key
endpoint> https://你的AccountID.r2.cloudflarestorage.com
上传目录:
rclone copy ./public cloudflare-r2:my-assets/public --progress
同步目录:
rclone sync ./public cloudflare-r2:my-assets/public --progress
列出文件:
rclone ls cloudflare-r2:my-assets
删除文件:
rclone delete cloudflare-r2:my-assets/public/old-file.txt
十四、Nginx 只允许 Cloudflare 回源,降低攻击成本
如果你没有使用 Tunnel,而是直接暴露源站 IP,建议源站只允许 Cloudflare IP 访问,拒绝其他请求。
1. 获取 Cloudflare IP 段
curl -s https://www.cloudflare.com/ips-v4 -o cloudflare-ips-v4.txt
curl -s https://www.cloudflare.com/ips-v6 -o cloudflare-ips-v6.txt
查看:
cat cloudflare-ips-v4.txt
cat cloudflare-ips-v6.txt
2. 生成 Nginx allow 配置
{
for ip in $(cat cloudflare-ips-v4.txt); do
echo "allow $ip;"
done
for ip in $(cat cloudflare-ips-v6.txt); do
echo "allow $ip;"
done
echo "deny all;"
} | sudo tee /etc/nginx/conf.d/cloudflare-allow.conf
3. 在 Nginx Server 中引用
编辑配置:
sudo nano /etc/nginx/conf.d/example.conf
示例:
server {
listen 80;
server_name www.example.com;
include /etc/nginx/conf.d/cloudflare-allow.conf;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $http_cf_connecting_ip;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
测试并重载:
sudo nginx -t
sudo systemctl reload nginx
十五、启用基础安全规则,减少被刷成本
如果网站被恶意请求、爬虫、扫描器频繁访问,源站成本会被拉高。Cloudflare 可以在边缘拦截大量无效请求。
1. 开启 Browser Integrity Check
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/browser_check" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "on"
}'
2. 设置安全等级
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/security_level" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "medium"
}'
可选值包括:
essentially_off
low
medium
high
under_attack
如果正在遭受攻击,可以临时设置为:
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/security_level" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "under_attack"
}'
十六、开启开发模式与关闭开发模式
开发模式会临时绕过 Cloudflare 缓存,适合排查问题,但长期打开会降低缓存命中率,增加源站成本。
开启开发模式:
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/development_mode" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "on"
}'
关闭开发模式:
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/development_mode" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"value": "off"
}'
正式环境一定不要长期开启开发模式。
十七、成本优化建议清单
下面是一份实用清单,可以按顺序执行。
缓存类
- 静态资源设置长期缓存;
- 图片、CSS、JS、字体文件设置 30 天以上缓存;
- HTML 页面按业务情况缓存 5 到 30 分钟;
- API 响应如果可以缓存,设置合理 TTL;
- 定期观察缓存命中率;
- 避免频繁全量清缓存;
- 使用文件 hash,例如
app.a8f3d2.js,减少清缓存需求。
安全类
- 开启 Cloudflare 代理;
- 隐藏源站 IP;
- 使用 Cloudflare Tunnel;
- 源站只允许 Cloudflare IP;
- 开启基础安全检查;
- 对登录、注册、搜索等接口做限流;
- 遭受攻击时启用 Under Attack 模式。
架构类
- 静态站点迁移到 Pages;
- 下载文件迁移到 R2;
- 简单 API 或重定向放到 Workers;
- 图床、附件、备份优先考虑 R2;
- 不要让大文件频繁回源;
- 尽量减少源站动态渲染压力。
运维类
- 使用 Wrangler 自动部署;
- 使用 API 管理规则;
- 使用 GitHub Actions 部署 Pages;
- 使用 Tunnel 减少防火墙配置;
- 用 Cloudflare 托管证书和 DNS;
- 定期检查无效 DNS 记录和 Worker 路由。
十八、一个完整的优化执行示例
假设你的网站是:
example.com
www.example.com
api.example.com
源站服务器运行:
- Nginx:80 端口;
- API:3000 端口;
- 静态资源目录:
/var/www/example。
你可以按下面顺序执行。
1. 设置变量
export CF_API_TOKEN="你的_Cloudflare_API_Token"
export CF_DOMAIN="example.com"
export CF_RECORD_NAME="www.example.com"
export CF_ORIGIN_IP="1.2.3.4"
2. 获取 Zone ID
export CF_ZONE_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=${CF_DOMAIN}" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" | jq -r '.result[0].id')
echo $CF_ZONE_ID
3. 开启安全和 SSL
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/ssl" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{"value":"strict"}'
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/always_use_https" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{"value":"on"}'
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/tls_1_3" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{"value":"on"}'
4. 开启压缩和浏览器缓存
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/brotli" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{"value":"on"}'
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/settings/browser_cache_ttl" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{"value":2592000}'
5. 创建静态资源缓存规则
curl -X POST "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/rulesets" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{
"name": "Cost Saving Static Cache",
"description": "Cache static assets to reduce origin traffic",
"kind": "zone",
"phase": "http_request_cache_settings",
"rules": [
{
"action": "set_cache_settings",
"expression": "(http.request.uri.path matches \"^/.*\\.(jpg|jpeg|png|gif|webp|avif|svg|css|js|woff|woff2|ttf|ico)$\")",
"description": "Cache static assets for 30 days",
"enabled": true,
"action_parameters": {
"cache": true,
"edge_ttl": {
"mode": "override_origin",
"default": 2592000
},
"browser_ttl": {
"mode": "override_origin",
"default": 2592000
}
}
}
]
}'
6. 安装 Tunnel
cloudflared tunnel login
cloudflared tunnel create example-tunnel
cloudflared tunnel route dns example-tunnel www.example.com
cloudflared tunnel route dns example-tunnel api.example.com
配置:
nano ~/.cloudflared/config.yml
写入:
tunnel: example-tunnel
credentials-file: /root/.cloudflared/你的-tunnel-id.json
ingress:
- hostname: www.example.com
service: http://localhost:80
- hostname: api.example.com
service: http://localhost:3000
- service: http_status:404
运行:
cloudflared tunnel run example-tunnel
安装服务:
sudo cloudflared service install
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
十九、如何判断是否真的降低成本?
Cloudflare 配置完成后,不要只看“是否能访问”,更重要的是看数据。
你需要关注:
1. 缓存命中率
在 Cloudflare Dashboard 中查看:
Analytics & Logs > Traffic > Cache
重点关注:
- Cached requests;
- Uncached requests;
- Cached bandwidth;
- Uncached bandwidth;
- Cache hit ratio。
如果缓存命中率低于 50%,说明还有优化空间。如果静态资源较多,通常可以做到 70% 以上。
2. 源站带宽是否下降
登录你的云服务器后台,查看出网流量曲线。如果 Cloudflare 生效,源站公网流量应该明显下降。
3. 源站 CPU 和内存是否下降
执行:
top
或:
htop
查看 Nginx、Node.js、PHP、Java 等进程压力是否下降。
也可以查看 Nginx 访问日志:
tail -f /var/log/nginx/access.log
如果 Cloudflare 缓存命中高,源站日志中的请求数应该减少。
4. 安全事件是否减少
查看 Cloudflare 安全日志:
Security > Events
如果大量扫描、恶意请求在 Cloudflare 边缘被拦截,就意味着这些请求没有打到源站,间接节省了服务器资源和防护成本。
二十、常见误区
误区一:只接入 DNS,不开启代理
如果 DNS 是灰色云朵,流量不会经过 Cloudflare,也不会降低带宽成本。必须开启橙色云朵代理。
误区二:所有页面都缓存
缓存不是越多越好。用户中心、订单页、购物车、后台管理、登录态页面不应该随意缓存。缓存策略要根据业务路径区分。
误区三:频繁清理全部缓存
每次全量清缓存都会导致大量请求重新回源,短时间内源站压力和带宽可能升高。推荐使用文件名 hash 或只清理指定 URL。
误区四:源站仍然暴露 IP
如果攻击者知道源站 IP,可以绕过 Cloudflare 直接攻击源站。建议使用 Cloudflare Tunnel,或者在防火墙、Nginx、安全组中只允许 Cloudflare IP 回源。
误区五:把 Workers 当成万能后端
Workers 很适合边缘轻量逻辑,但不适合所有复杂后端业务。成本优化的关键是把合适的逻辑放到边缘,而不是盲目迁移所有系统。
总结
Cloudflare 降低成本的核心不是某一个按钮,而是一套组合方案:
- 用 CDN 缓存减少源站带宽;
- 用 Cache Rules 提高缓存命中率;
- 用 Brotli、Minify 减少传输体积;
- 用 SSL/TLS 托管减少证书维护;
- 用 Tunnel 隐藏源站降低安全风险;
- 用 Pages 替代静态网站服务器;
- 用 Workers 承担轻量边缘逻辑;
- 用 R2 降低对象存储出网成本;
- 用 API 和 Wrangler 实现自动化管理。
如果你的网站以静态资源、文档、博客、下载、图片为主,Cloudflare 带来的成本下降会非常明显;如果是动态业务,也可以通过缓存、隧道、安全规则和边缘逻辑降低源站压力。
最终目标不是“把所有东西都放到 Cloudflare”,而是让 Cloudflare 承担它最擅长的部分:缓存、安全、边缘计算、流量入口和静态资源分发。这样既能降低服务器和带宽费用,也能提升访问速度和稳定性。