Cloudflare 抗高并发实战:从缓存、限流到源站防护完整配置指南
Cloudflare 高并发解决方案|附完整命令
在业务访问量快速增长、活动秒杀、接口突发请求、爬虫扫描、DDoS 攻击或海外访问波动等场景下,网站很容易出现 源站 CPU 飙升、带宽打满、连接数耗尽、数据库压力过大、接口响应变慢甚至宕机 等问题。
Cloudflare 作为全球 CDN、安全防护与边缘网络平台,可以帮助我们在高并发场景下完成以下目标:
- 缓存静态资源,减少源站压力;
- 隐藏源站 IP,避免被直接攻击;
- 使用 WAF、Rate Limit、Bot 管理规则拦截异常流量;
- 使用边缘缓存、页面规则、Cache Rules 提升命中率;
- 使用 Argo、Tiered Cache、Polish、Brotli 优化访问速度;
- 与 Nginx、负载均衡、Redis、数据库优化配合,构建完整高并发架构。
本文将从 架构设计、Cloudflare 配置、源站优化、缓存策略、安全防护、命令示例、排查方法 等方面,给出一套相对完整的 Cloudflare 高并发解决方案。
一、适用场景
本方案适合以下业务:
- 官网、博客、文档站、下载站;
- 电商活动页、秒杀页、营销落地页;
- API 接口服务;
- 图片、视频、JS、CSS 等静态资源分发;
- WordPress、Typecho、Laravel、ThinkPHP、Next.js、Nuxt 等 Web 应用;
- 海外访问量较多的网站;
- 经常遭遇 CC 攻击、恶意爬虫、扫描器的网站。
需要注意的是,Cloudflare 并不是万能的。
如果你的系统瓶颈在数据库设计、代码逻辑、接口没有缓存、源站配置过低,Cloudflare 只能缓解问题,不能彻底替代后端架构优化。
一个成熟的高并发方案,通常需要同时做好:
用户请求
↓
Cloudflare CDN / WAF / Rate Limit / Cache
↓
负载均衡 SLB / Nginx
↓
应用服务器集群
↓
Redis / MQ / 数据库 / 对象存储
二、整体架构设计
推荐架构如下:
用户
↓
Cloudflare DNS
↓
Cloudflare CDN + WAF + Bot 防护 + Rate Limit
↓
源站 Nginx 反向代理
↓
应用服务:PHP-FPM / Node.js / Java / Go
↓
Redis 缓存
↓
MySQL / PostgreSQL / MongoDB
↓
对象存储:S3 / R2 / OSS / COS
核心原则:
- 能在 Cloudflare 缓存的内容,不回源;
- 能在 Nginx 缓存的内容,不进应用;
- 能在 Redis 缓存的数据,不查数据库;
- 高频接口必须限流;
- 源站 IP 必须隐藏;
- 所有真实 IP 只信任 Cloudflare 传递;
- 静态资源与动态接口分开处理。
三、Cloudflare DNS 基础配置
首先需要将域名接入 Cloudflare。
1. 添加站点
进入 Cloudflare 控制台:
Websites → Add a site → 输入域名 → 选择套餐 → 扫描 DNS
2. 修改域名 NS
在域名注册商处,将 NS 修改为 Cloudflare 提供的 NS,例如:
alice.ns.cloudflare.com
bob.ns.cloudflare.com
等待 DNS 生效,一般需要几分钟到数小时。
3. 配置 DNS 记录
推荐配置:
| 类型 | 名称 | 指向 | 代理状态 |
|---|---|---|---|
| A | @ | 源站 IP | Proxied |
| A | www | 源站 IP | Proxied |
| A | api | 源站 IP | Proxied |
| CNAME | static | example.com | Proxied |
注意:
只有开启橙色云朵 Proxied,流量才会经过 Cloudflare。
如果是灰色云朵 DNS only,则 Cloudflare 只负责 DNS 解析,不提供 CDN 与防护。
四、源站安全:只允许 Cloudflare 访问
高并发场景下,最重要的一步是 隐藏源站 IP。
如果攻击者直接访问源站 IP,则 Cloudflare 的 WAF、Rate Limit、CDN 都会失效。
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. 使用 UFW 只允许 Cloudflare IP
如果服务器使用 Ubuntu/Debian,可使用 UFW。
安装 UFW:
sudo apt update
sudo apt install ufw -y
默认拒绝入站:
sudo ufw default deny incoming
sudo ufw default allow outgoing
允许 SSH,避免自己被锁在外面:
sudo ufw allow 22/tcp
允许 Cloudflare IPv4 访问 80 和 443:
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
sudo ufw allow from $ip to any port 80 proto tcp
sudo ufw allow from $ip to any port 443 proto tcp
done
允许 Cloudflare IPv6 访问 80 和 443:
for ip in $(curl -s https://www.cloudflare.com/ips-v6); do
sudo ufw allow from $ip to any port 80 proto tcp
sudo ufw allow from $ip to any port 443 proto tcp
done
启用 UFW:
sudo ufw enable
sudo ufw status verbose
3. 使用 iptables 配置
如果你使用 iptables,可以执行:
sudo iptables -F
sudo iptables -X
允许本地回环:
sudo iptables -A INPUT -i lo -j ACCEPT
允许已建立连接:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
允许 SSH:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
允许 Cloudflare IPv4 访问 HTTP/HTTPS:
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
sudo iptables -A INPUT -p tcp -s $ip --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp -s $ip --dport 443 -j ACCEPT
done
拒绝其他访问:
sudo iptables -A INPUT -p tcp --dport 80 -j DROP
sudo iptables -A INPUT -p tcp --dport 443 -j DROP
sudo iptables -A INPUT -j DROP
保存规则:
sudo apt install iptables-persistent -y
sudo netfilter-persistent save
sudo netfilter-persistent reload
五、Nginx 高并发基础优化
Cloudflare 缓解的是边缘访问压力,源站仍然要具备一定承载能力。
1. 安装 Nginx
Ubuntu/Debian:
sudo apt update
sudo apt install nginx -y
CentOS/Rocky Linux:
sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
查看状态:
sudo systemctl status nginx
2. 调整系统打开文件数
编辑:
sudo nano /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
编辑 systemd 配置:
sudo mkdir -p /etc/systemd/system/nginx.service.d
sudo nano /etc/systemd/system/nginx.service.d/override.conf
写入:
[Service]
LimitNOFILE=65535
重新加载:
sudo systemctl daemon-reload
sudo systemctl restart nginx
3. 优化 Nginx 主配置
编辑:
sudo nano /etc/nginx/nginx.conf
推荐配置示例:
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 8192;
multi_accept on;
use epoll;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30;
keepalive_requests 10000;
types_hash_max_size 4096;
server_tokens off;
client_max_body_size 50m;
client_body_timeout 15s;
client_header_timeout 15s;
send_timeout 30s;
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types
text/plain
text/css
application/json
application/javascript
text/xml
application/xml
application/xml+rss
image/svg+xml;
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
测试配置:
sudo nginx -t
sudo systemctl reload nginx
六、恢复真实用户 IP
使用 Cloudflare 后,源站看到的访问 IP 默认是 Cloudflare 节点 IP。
如果不恢复真实 IP,日志分析、限流、安全策略都会不准确。
1. 安装 realip 模块
通常 Nginx 默认包含 ngx_http_realip_module。检查:
nginx -V 2>&1 | grep realip
2. 配置 Cloudflare Real IP
新建配置文件:
sudo nano /etc/nginx/conf.d/cloudflare-realip.conf
写入:
real_ip_header CF-Connecting-IP;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
测试并重载:
sudo nginx -t
sudo systemctl reload nginx
七、Cloudflare 缓存策略
高并发的关键是提高缓存命中率。
1. 静态资源缓存
推荐对以下资源设置长缓存:
*.css
*.js
*.jpg
*.jpeg
*.png
*.gif
*.webp
*.svg
*.ico
*.woff
*.woff2
*.ttf
*.mp4
*.zip
Nginx 配置示例:
location ~* \.(?:css|js|jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|mp4|zip)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
access_log off;
}
重载:
sudo nginx -t
sudo systemctl reload nginx
2. HTML 页面缓存
如果是静态站、文档站、博客详情页,可以考虑缓存 HTML。
在 Cloudflare 中设置:
Rules → Cache Rules → Create rule
条件示例:
Hostname equals example.com
AND URI Path does not start with /admin
AND URI Path does not start with /api
动作:
Cache eligibility: Eligible for cache
Edge TTL: 1 hour / 4 hours / 1 day
Browser TTL: 30 minutes
如果是登录态页面、用户中心、订单页,不建议缓存 HTML,否则可能造成用户数据串页。
3. API 缓存策略
对于读多写少的公开 API,例如:
/api/articles
/api/categories
/api/products
可以设置短缓存:
Edge TTL: 30 秒 ~ 5 分钟
对于以下接口不要缓存:
/api/login
/api/logout
/api/order
/api/payment
/api/user
/api/admin
在 Nginx 可添加:
location ^~ /api/ {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;
}
八、Cloudflare WAF 与限流
高并发并不一定都是正常用户,有时是爬虫、扫描器或 CC 攻击。
Cloudflare 的 WAF 和 Rate Limit 可以有效降低恶意请求进入源站的概率。
1. 开启托管规则
进入:
Security → WAF → Managed rules
建议开启:
Cloudflare Managed Ruleset
Cloudflare OWASP Core Ruleset
如果出现误拦截,可以通过日志查看具体规则,然后针对路径或参数创建例外规则。
2. 创建基础防护规则
路径包含后台时要求挑战:
Security → WAF → Custom rules → Create rule
规则:
URI Path starts with /admin
动作:
Managed Challenge
也可以对 WordPress 后台:
URI Path contains /wp-admin
OR URI Path equals /wp-login.php
动作:
Managed Challenge
3. 拦截高风险国家或地区
如果业务只面向特定区域,可以限制无关地区访问。
示例:
Country not in CN, HK, SG, US
动作可选择:
Managed Challenge
不建议直接全部 Block,除非非常明确无业务需求。
4. Rate Limiting 限流策略
典型规则:
登录接口限流
URI Path equals /api/login
限制:
10 requests per 1 minute per IP
动作:
Managed Challenge 或 Block
搜索接口限流
URI Path starts with /api/search
限制:
30 requests per 1 minute per IP
全站异常请求限流
Hostname equals example.com
限制:
300 requests per 1 minute per IP
注意:
限流阈值必须结合业务实际情况。
如果阈值过低,可能误伤真实用户;如果过高,防护效果有限。
九、使用 Cloudflare API 批量配置
以下命令适合需要自动化管理的场景。
1. 准备 API Token
在 Cloudflare 后台创建 API Token:
My Profile → API Tokens → Create Token
建议权限:
Zone.Zone Read
Zone.DNS Edit
Zone.Cache Purge
Zone.WAF Edit
设置环境变量:
export CF_API_TOKEN="你的_API_TOKEN"
export CF_ZONE_ID="你的_ZONE_ID"
export CF_DOMAIN="example.com"
测试:
curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" | jq
安装 jq:
sudo apt update
sudo apt install jq -y
2. 清理全站缓存
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}'
3. 清理指定 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://example.com/index.html",
"https://example.com/assets/app.css",
"https://example.com/assets/app.js"
]
}'
4. 创建 DNS 记录
添加 A 记录:
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": "www",
"content": "1.2.3.4",
"ttl": 1,
"proxied": true
}'
添加 CNAME:
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": "CNAME",
"name": "static",
"content": "example.com",
"ttl": 1,
"proxied": true
}'
十、Cloudflare 页面与缓存规则建议
不同类型业务建议如下。
1. 静态站点
Cache Everything
Edge TTL: 1 day ~ 30 days
Browser TTL: 1 day ~ 7 days
Brotli: On
Always Online: On
2. WordPress
建议:
/wp-admin/* 不缓存,Managed Challenge
/wp-login.php 不缓存,限流
/wp-content/uploads/* 长缓存
/wp-content/themes/* 长缓存
/wp-content/plugins/* 长缓存
文章页可缓存 HTML,但登录用户不缓存
3. API 服务
建议:
/api/login 不缓存,严格限流
/api/user 不缓存
/api/order 不缓存
/api/public/* 可短缓存
/api/search 可短缓存 + 限流
4. 电商秒杀活动页
建议:
活动页 HTML 缓存 30 秒 ~ 5 分钟
商品详情缓存 30 秒 ~ 10 分钟
库存接口不缓存,但必须限流
下单接口不缓存,需排队、令牌桶、风控
静态资源长期缓存
Cloudflare 可以承担大量页面访问,但真正的秒杀系统还必须依赖后端削峰,例如 Redis 预扣库存、消息队列异步下单、用户排队、接口签名等。
十一、源站反向代理与缓存配置
如果源站后面还有应用服务,可以使用 Nginx 反向代理。
1. 配置 upstream
upstream backend_app {
least_conn;
server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
server 127.0.0.1:3001 max_fails=3 fail_timeout=30s;
keepalive 64;
}
2. 配置代理站点
server {
listen 80;
server_name example.com www.example.com;
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
location / {
proxy_pass http://backend_app;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
location ~* \.(?:css|js|jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
access_log off;
try_files $uri =404;
}
}
启用:
sudo ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/example.conf
sudo nginx -t
sudo systemctl reload nginx
十二、开启 HTTPS 与 SSL 模式
Cloudflare SSL 推荐使用:
SSL/TLS → Overview → Full(strict)
不要长期使用:
Flexible
因为 Flexible 模式下,用户到 Cloudflare 是 HTTPS,但 Cloudflare 到源站是 HTTP,不够安全,也容易出现重定向循环。
1. 使用 Cloudflare Origin Certificate
在 Cloudflare 后台:
SSL/TLS → Origin Server → Create Certificate
将证书保存到服务器:
sudo mkdir -p /etc/nginx/ssl
sudo nano /etc/nginx/ssl/cloudflare-origin.pem
sudo nano /etc/nginx/ssl/cloudflare-origin.key
设置权限:
sudo chmod 600 /etc/nginx/ssl/cloudflare-origin.key
Nginx HTTPS 配置:
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/nginx/ssl/cloudflare-origin.pem;
ssl_certificate_key /etc/nginx/ssl/cloudflare-origin.key;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
proxy_pass http://backend_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
重载:
sudo nginx -t
sudo systemctl reload nginx
十三、性能测试与缓存命中检查
1. 查看响应头
curl -I https://example.com
重点关注:
cf-cache-status: HIT
cf-cache-status: MISS
cf-cache-status: BYPASS
cf-ray
server: cloudflare
如果是:
cf-cache-status: HIT
说明命中 Cloudflare 缓存。
如果长期是:
MISS 或 BYPASS
需要检查缓存规则、响应头、Cookie、路径规则等。
2. 压测源站前注意事项
如果要测试自己的服务,请控制规模,避免影响线上业务。
推荐先在测试环境执行。
安装 wrk:
sudo apt update
sudo apt install wrk -y
测试示例:
wrk -t4 -c200 -d30s https://example.com/
参数说明:
-t4 使用 4 个线程
-c200 保持 200 个并发连接
-d30s 持续 30 秒
如果测试 API:
wrk -t4 -c100 -d30s https://example.com/api/articles
十四、常见问题排查
1. 出现 522
522 通常表示 Cloudflare 连接源站超时。
排查:
sudo systemctl status nginx
sudo ss -lntp
sudo tail -n 100 /var/log/nginx/error.log
可能原因:
- 源站宕机;
- 防火墙误拦截 Cloudflare;
- Nginx 连接数不足;
- 应用服务响应太慢;
- 数据库阻塞。
2. 出现 521
521 表示源站拒绝连接。
检查 Nginx 是否监听:
sudo ss -lntp | grep nginx
检查防火墙:
sudo ufw status verbose
3. 出现 524
524 表示 Cloudflare 已连接源站,但源站响应超时。
解决方向:
- 优化慢接口;
- 增加缓存;
- 将耗时任务改为异步;
- 数据库加索引;
- 减少单请求执行时间。
查看慢请求:
sudo tail -n 200 /var/log/nginx/access.log
4. 缓存不生效
查看响应头:
curl -I https://example.com/assets/app.js
检查是否存在:
Cache-Control: no-cache
Cache-Control: private
Set-Cookie
如果响应带有 private 或大量 Set-Cookie,Cloudflare 可能不会缓存。
十五、推荐上线清单
上线前建议逐项确认:
- [ ] DNS 记录已开启 Proxied;
- [ ] 源站 IP 未公开;
- [ ] 防火墙只允许 Cloudflare 访问 80/443;
- [ ] Nginx 已恢复真实用户 IP;
- [ ] 静态资源已设置长缓存;
- [ ] HTML 页面缓存策略已区分登录与未登录;
- [ ] API 登录、搜索、下单接口已限流;
- [ ] WAF 托管规则已开启;
- [ ] SSL 模式为 Full(strict);
- [ ] 源站 Nginx worker、连接数、文件句柄已优化;
- [ ] 数据库与 Redis 已完成基础优化;
- [ ] 已建立缓存清理脚本;
- [ ] 已监控 5xx、命中率、带宽、请求量。
十六、完整命令汇总
以下是一组常用初始化命令,可根据实际情况修改。
sudo apt update
sudo apt install nginx ufw jq curl -y
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
sudo ufw allow from $ip to any port 80 proto tcp
sudo ufw allow from $ip to any port 443 proto tcp
done
for ip in $(curl -s https://www.cloudflare.com/ips-v6); do
sudo ufw allow from $ip to any port 80 proto tcp
sudo ufw allow from $ip to any port 443 proto tcp
done
sudo ufw enable
sudo ufw status verbose
sudo mkdir -p /etc/systemd/system/nginx.service.d
cat <
创建 Cloudflare Real IP 配置:
cat <
清理 Cloudflare 缓存:
export CF_API_TOKEN="你的_API_TOKEN"
export CF_ZONE_ID="你的_ZONE_ID"
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}'
总结
Cloudflare 高并发解决方案的核心不是简单“套一层 CDN”,而是围绕 缓存、防护、限流、源站隔离、真实 IP、Nginx 优化、后端削峰 构建完整体系。
推荐优先级如下:
- 域名接入 Cloudflare,并开启代理;
- 隐藏源站 IP,只允许 Cloudflare 回源;
- 静态资源长缓存,HTML 按业务选择缓存;
- 开启 WAF、Bot 防护和 Rate Limit;
- 源站 Nginx 优化连接数、文件句柄和缓存头;
- API 做限流、鉴权、Redis 缓存;
- 对秒杀、抢购、支付类业务使用队列和异步削峰;
- 持续监控 Cloudflare 命中率、5xx 错误和源站负载。
只要缓存策略合理、源站安全边界清晰、接口限流到位,Cloudflare 可以显著提升系统在高并发场景下的稳定性与抗压能力。