上一篇 下一篇 分享链接 返回 返回顶部

Cloudflare 扛高并发实战:缓存、限流、防护与源站配置一次配齐

发布人:慈云数据-客服中心 发布时间:23小时前 阅读量:4

Cloudflare 高并发解决方案|附配置文件

在互联网业务中,“高并发”几乎是所有网站、API、应用服务都会遇到的问题。尤其是活动页、秒杀系统、内容站、下载站、跨境电商、SaaS 平台以及接口型服务,一旦流量在短时间内暴涨,源站很容易出现 CPU 飙升、带宽打满、数据库连接耗尽、Nginx 502/504、接口响应变慢等问题。

Cloudflare 作为全球知名的 CDN、安全防护与边缘网络平台,在应对高并发访问、抗突发流量、缓存静态资源、隐藏源站 IP、防御恶意请求等方面具有非常强的能力。合理使用 Cloudflare,可以将大量请求直接拦截或响应在边缘节点,显著降低源站压力。

本文将围绕 Cloudflare 高并发解决方案 展开,结合实际生产环境,介绍一套适用于中小型网站、API 服务、WordPress、Laravel、Node.js、Java、Go 后端等场景的优化方案,并附带可直接参考的配置文件。


一、Cloudflare 在高并发架构中的作用

在传统架构中,请求链路通常是:

用户浏览器 → 源站服务器 → 应用服务 → 数据库/缓存

如果没有 CDN 和边缘防护,所有请求都会直接打到源站。一旦访问量突然增加,源站需要同时处理静态资源、动态接口、恶意扫描、爬虫请求、数据库查询等压力。

接入 Cloudflare 后,请求链路变为:

用户浏览器 → Cloudflare 边缘节点 → 源站服务器 → 应用服务 → 数据库/缓存

Cloudflare 可以承担以下任务:

  1. 缓存静态资源
    例如 JS、CSS、图片、字体、视频片段等资源可以直接由 Cloudflare 边缘节点返回。

  2. 隐藏源站 IP
    用户无法直接访问真实服务器,降低源站被攻击的风险。

  3. 抵御 DDoS 和恶意流量
    Cloudflare 可以在网络边缘过滤大规模异常请求。

  4. WAF Web 应用防火墙
    拦截 SQL 注入、XSS、恶意扫描、漏洞探测等请求。

  5. 限速 Rate Limiting
    对登录、注册、短信、API 等接口进行请求频率限制。

  6. 缓存 HTML 页面
    对内容变化不频繁的网站,可以缓存 HTML,大幅降低源站压力。

  7. 边缘计算 Workers
    在 Cloudflare 边缘节点进行请求处理、鉴权、跳转、灰度分流等操作。


二、高并发场景下的核心优化思路

高并发优化不是单点配置,而是系统工程。使用 Cloudflare 时,需要从以下几个层面进行设计:

DNS 接入
↓
SSL/TLS 配置
↓
缓存策略
↓
WAF 防护
↓
限速规则
↓
源站防护
↓
Nginx/应用服务优化
↓
数据库和缓存优化

其中 Cloudflare 主要解决的是“入口层”和“边缘层”的问题,但如果源站本身配置非常差,只依赖 Cloudflare 也无法彻底解决所有高并发问题。


三、Cloudflare DNS 接入配置

首先需要将域名接入 Cloudflare,并把域名 NS 修改为 Cloudflare 提供的名称服务器。

在 Cloudflare DNS 面板中添加记录,例如:

类型 名称 内容 代理状态
A example.com 1.2.3.4 Proxied
A www 1.2.3.4 Proxied
CNAME static example.com Proxied
CNAME api example.com Proxied

需要注意:

  • 橙色云朵表示开启 Cloudflare 代理;
  • 灰色云朵表示仅 DNS 解析,不经过 Cloudflare;
  • 对外业务域名建议开启 Proxied;
  • 邮件相关记录不要开启代理;
  • 源站 IP 不应直接暴露在公开配置、Git 仓库或错误日志中。

四、SSL/TLS 推荐配置

Cloudflare SSL/TLS 模式建议使用:

Full 或 Full (strict)

生产环境强烈推荐:

Full (strict)

这表示:

用户 → Cloudflare:HTTPS
Cloudflare → 源站:HTTPS

如果选择 Flexible,则 Cloudflare 到源站之间是 HTTP,在登录、支付、后台管理等业务中存在安全隐患,也容易导致重定向循环。

源站证书建议

可以使用:

  1. Cloudflare Origin Certificate;
  2. Let's Encrypt 免费证书;
  3. 商业 SSL 证书。

如果使用 Cloudflare Origin Certificate,它只被 Cloudflare 信任,不适合用户直接访问源站,但非常适合隐藏源站的生产环境。


五、Cloudflare 缓存策略设计

高并发优化中,缓存是最重要的一环。原则是:

能在浏览器缓存的,不到 Cloudflare;能在 Cloudflare 缓存的,不到源站;能在应用缓存的,不查数据库。

1. 静态资源缓存

静态资源包括:

*.css
*.js
*.jpg
*.jpeg
*.png
*.gif
*.webp
*.svg
*.ico
*.woff
*.woff2
*.ttf
*.eot
*.mp4

建议设置较长缓存时间,例如 7 天、30 天甚至 1 年。

在 Cloudflare Cache Rules 中可配置:

if URI Path ends with .css
or URI Path ends with .js
or URI Path ends with .jpg
or URI Path ends with .png
or URI Path ends with .webp
then
Cache eligibility: Eligible for cache
Edge TTL: 30 days
Browser TTL: 7 days

2. HTML 页面缓存

对于内容型网站、文档站、博客、营销页,可以缓存 HTML 页面。

适合缓存的页面:

/
 /article/*
 /blog/*
 /docs/*
 /product/*

不适合缓存的页面:

/admin/*
/user/*
/login
/register
/cart
/checkout
/api/*

如果 HTML 可以被缓存,高并发能力会提升非常明显。因为大量用户访问页面时,Cloudflare 可以直接返回缓存,不需要请求源站。

3. API 缓存

API 是否缓存取决于业务。

可以缓存的 API:

GET /api/news
GET /api/products
GET /api/categories
GET /api/config

不建议缓存的 API:

POST /api/login
POST /api/pay
GET /api/user/profile
POST /api/order/create

对于公共 GET API,可以设置短缓存,例如 10 秒、30 秒、60 秒。即使只缓存 10 秒,也能在高并发下显著削峰。


六、Cloudflare Cache Rules 示例

以下是一个适合普通网站的缓存规则设计。

规则一:缓存静态资源

规则名称:Cache Static Assets

条件:
(http.request.uri.path matches ".*\.(css|js|jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|eot|mp4)$")

动作:
Cache eligibility: Eligible for cache
Edge TTL: 30 days
Browser TTL: 7 days
Respect origin cache-control: enabled

规则二:缓存公开 HTML 页面

规则名称:Cache Public HTML

条件:
(http.request.uri.path eq "/")
or (http.request.uri.path starts_with "/blog/")
or (http.request.uri.path starts_with "/article/")
or (http.request.uri.path starts_with "/docs/")

动作:
Cache eligibility: Eligible for cache
Edge TTL: 10 minutes
Browser TTL: 1 minute
Cache key: Include query string only for selected parameters

规则三:绕过后台和用户页面

规则名称:Bypass Private Pages

条件:
(http.request.uri.path starts_with "/admin")
or (http.request.uri.path starts_with "/user")
or (http.request.uri.path starts_with "/login")
or (http.request.uri.path starts_with "/register")
or (http.request.uri.path starts_with "/cart")
or (http.request.uri.path starts_with "/checkout")
or (http.request.uri.path starts_with "/api/auth")

动作:
Cache eligibility: Bypass cache

规则四:短缓存公共 API

规则名称:Cache Public API

条件:
(http.request.method eq "GET")
and (
  (http.request.uri.path starts_with "/api/public/")
  or (http.request.uri.path starts_with "/api/products")
  or (http.request.uri.path starts_with "/api/categories")
)

动作:
Cache eligibility: Eligible for cache
Edge TTL: 30 seconds
Browser TTL: 10 seconds

七、Cloudflare WAF 防护配置

高并发场景中,除了正常用户流量,还会有大量恶意请求,包括:

  • 漏洞扫描;
  • 暴力破解;
  • CC 攻击;
  • 爬虫抓取;
  • SQL 注入;
  • 文件探测;
  • 后台路径扫描。

建议开启 Cloudflare 的 Managed Rules,并配置自定义 WAF 规则。

1. 拦截常见扫描路径

规则名称:Block Common Scan Paths

条件:
(http.request.uri.path contains "/wp-admin/install.php")
or (http.request.uri.path contains "/.env")
or (http.request.uri.path contains "/phpinfo.php")
or (http.request.uri.path contains "/config.php")
or (http.request.uri.path contains "/vendor/phpunit")
or (http.request.uri.path contains "/.git")
or (http.request.uri.path contains "/server-status")

动作:
Block

2. 限制后台访问国家或 IP

如果后台只给固定 IP 使用,可以配置:

规则名称:Protect Admin

条件:
(http.request.uri.path starts_with "/admin")
and not ip.src in {203.0.113.10 203.0.113.11}

动作:
Block

如果无法固定 IP,可以改为 Managed Challenge:

规则名称:Challenge Admin

条件:
(http.request.uri.path starts_with "/admin")

动作:
Managed Challenge

3. 拦截异常 User-Agent

规则名称:Block Bad Bots

条件:
(lower(http.user_agent) contains "sqlmap")
or (lower(http.user_agent) contains "nikto")
or (lower(http.user_agent) contains "acunetix")
or (lower(http.user_agent) contains "masscan")
or (lower(http.user_agent) contains "zgrab")
or (http.user_agent eq "")

动作:
Block

4. 对高风险地区进行挑战

规则名称:Challenge High Risk Traffic

条件:
(ip.geoip.country in {"T1" "XX"})
and not cf.client.bot

动作:
Managed Challenge

注意:地区策略需要结合实际业务,不建议盲目封禁正常用户所在区域。


八、Cloudflare Rate Limiting 限速策略

Rate Limiting 是抗高并发恶意请求的重要手段。尤其是登录、注册、短信、邮箱验证码、搜索、评论、支付回调等接口。

1. 登录接口限速

规则名称:Limit Login

条件:
(http.request.uri.path eq "/login")
or (http.request.uri.path eq "/api/login")

限制:
10 requests / 1 minute / IP

动作:
Managed Challenge 或 Block

2. 注册接口限速

规则名称:Limit Register

条件:
(http.request.uri.path eq "/register")
or (http.request.uri.path eq "/api/register")

限制:
5 requests / 1 minute / IP

动作:
Managed Challenge

3. 搜索接口限速

搜索接口容易拖垮数据库,建议限制:

规则名称:Limit Search

条件:
(http.request.uri.path starts_with "/search")
or (http.request.uri.path starts_with "/api/search")

限制:
30 requests / 1 minute / IP

动作:
Block for 10 minutes

4. API 全局限速

规则名称:Limit API

条件:
(http.request.uri.path starts_with "/api/")

限制:
300 requests / 1 minute / IP

动作:
Managed Challenge 或 Block

实际阈值要根据业务调整。如果是 App API 或企业客户 API,不应简单按 IP 限制,可以结合 Token、Header、路径等维度进行设计。


九、源站只允许 Cloudflare IP 访问

接入 Cloudflare 后,非常重要的一步是:源站防火墙只允许 Cloudflare IP 访问 80/443 端口

否则攻击者如果知道源站 IP,可以绕过 Cloudflare 直接攻击服务器。

Cloudflare 官方 IP 地址段地址:

https://www.cloudflare.com/ips-v4
https://www.cloudflare.com/ips-v6

Linux iptables 配置示例

以下是一个简化版示例,实际请以 Cloudflare 最新 IP 段为准。

#!/bin/bash

# 清空旧规则
iptables -F

# 允许本机回环
iptables -A INPUT -i lo -j ACCEPT

# 允许已建立连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 允许 SSH,仅建议固定办公 IP
iptables -A INPUT -p tcp -s 203.0.113.10 --dport 22 -j ACCEPT

# 允许 Cloudflare IPv4 访问 HTTP/HTTPS
for ip in \
173.245.48.0/20 \
103.21.244.0/22 \
103.22.200.0/22 \
103.31.4.0/22 \
141.101.64.0/18 \
108.162.192.0/18 \
190.93.240.0/20 \
188.114.96.0/20 \
197.234.240.0/22 \
198.41.128.0/17 \
162.158.0.0/15 \
104.16.0.0/13 \
104.24.0.0/14 \
172.64.0.0/13 \
131.0.72.0/22
do
  iptables -A INPUT -p tcp -s $ip --dport 80 -j ACCEPT
  iptables -A INPUT -p tcp -s $ip --dport 443 -j ACCEPT
done

# 拒绝其他 HTTP/HTTPS 访问
iptables -A INPUT -p tcp --dport 80 -j DROP
iptables -A INPUT -p tcp --dport 443 -j DROP

# 默认拒绝
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

上线前请务必确认 SSH 放行规则正确,否则可能把自己锁在服务器外。


十、Nginx 高并发优化配置

Cloudflare 可以挡住大部分压力,但源站 Nginx 仍然需要优化。以下配置适用于常见 Linux 服务器。

1. /etc/nginx/nginx.conf 示例

user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 65535;
    multi_accept on;
    use epoll;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    server_tokens off;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    keepalive_timeout 30;
    keepalive_requests 10000;

    client_header_timeout 10s;
    client_body_timeout 10s;
    send_timeout 10s;

    client_max_body_size 20m;
    client_body_buffer_size 128k;

    open_file_cache max=100000 inactive=60s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    gzip on;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_vary on;
    gzip_types
        text/plain
        text/css
        application/json
        application/javascript
        application/xml
        application/rss+xml
        image/svg+xml;

    # 获取真实客户端 IP
    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;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_cf_ray"';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;

    include /etc/nginx/conf.d/*.conf;
}

2. 站点配置示例

server {
    listen 80;
    server_name example.com www.example.com;

    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    root /var/www/example/public;
    index index.html index.php;

    ssl_certificate     /etc/ssl/certs/origin.pem;
    ssl_certificate_key /etc/ssl/private/origin.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;

    add_header X-Frame-Options SAMEORIGIN always;
    add_header X-Content-Type-Options nosniff always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location ~* \.(css|js|jpg|jpeg|png|gif|webp|svg|ico|woff|woff2|ttf|eot)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000, immutable";
        access_log off;
        try_files $uri =404;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_connect_timeout 5s;
        fastcgi_send_timeout 30s;
        fastcgi_read_timeout 30s;

        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

十一、PHP-FPM 高并发配置示例

如果后端使用 PHP,例如 WordPress、Laravel、ThinkPHP 等,需要优化 PHP-FPM。

配置文件通常位于:

/etc/php/8.2/fpm/pool.d/www.conf

示例:

[www]
user = www-data
group = www-data

listen = /run/php/php8.2-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 80
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 1000

request_terminate_timeout = 30s
request_slowlog_timeout = 3s
slowlog = /var/log/php-fpm/slow.log

php_admin_value[memory_limit] = 256M
php_admin_value[upload_max_filesize] = 20M
php_admin_value[post_max_size] = 20M

pm.max_children 不要盲目设置过大,需要根据内存估算。例如单个 PHP 进程平均占用 80MB,服务器可用内存 6GB,则:

6000 / 80 ≈ 75

因此设置为 70 到 80 比较合理。


十二、Node.js 反向代理配置示例

如果源站后端是 Node.js,可以使用 Nginx 反向代理。

upstream node_backend {
    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    keepalive 64;
}

server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate     /etc/ssl/certs/origin.pem;
    ssl_certificate_key /etc/ssl/private/origin.key;

    location / {
        proxy_pass http://node_backend;
        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 X-Forwarded-Proto $scheme;

        proxy_set_header Connection "";

        proxy_connect_timeout 5s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

        proxy_buffering on;
        proxy_buffers 32 16k;
        proxy_buffer_size 32k;
    }
}

Node.js 应用建议配合 PM2 或 systemd 管理,并开启多进程。

PM2 示例:

pm2 start app.js -i max --name example-api
pm2 save
pm2 startup

十三、Cloudflare Workers 边缘限流示例

如果使用 Cloudflare Workers,可以在边缘层做更灵活的处理。例如对特定路径进行简单拦截、跳转或鉴权。

下面是一个简单的 Workers 示例,用于拦截异常路径:

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const path = url.pathname.toLowerCase();

    const blockedPaths = [
      "/.env",
      "/.git",
      "/phpinfo.php",
      "/server-status"
    ];

    if (blockedPaths.some(p => path.includes(p))) {
      return new Response("Forbidden", { status: 403 });
    }

    return fetch(request);
  }
}

如果要做真正的分布式限流,可以结合 Workers KV、Durable Objects 或 Cloudflare Rate Limiting 产品实现。


十四、数据库与应用层优化建议

Cloudflare 再强,也无法替代数据库优化。如果动态请求每次都查数据库,高并发时仍然可能崩溃。

建议:

  1. 使用 Redis 缓存热点数据
    首页数据、配置项、商品列表、文章详情、分类信息都可以缓存。

  2. 避免慢查询
    为高频查询字段建立索引,避免全表扫描。

  3. 读写分离
    高并发读场景可以使用只读副本。

  4. 异步化任务
    邮件发送、短信通知、订单后处理、日志写入可以进入队列。

  5. 接口防抖与幂等
    提交订单、支付回调、注册等接口必须具备幂等能力。

  6. 页面静态化
    对营销页、文章页、商品详情页尽量生成静态 HTML。


十五、推荐的整体架构

对于中小型业务,推荐架构如下:

用户
↓
Cloudflare DNS / CDN / WAF / Rate Limiting
↓
Nginx 源站入口
↓
应用服务 PHP-FPM / Node.js / Java / Go
↓
Redis 缓存
↓
MySQL / PostgreSQL
↓
对象存储 / 日志系统

如果业务流量更大,可以升级为:

用户
↓
Cloudflare
↓
负载均衡
↓
多台 Web 服务
↓
Redis Cluster
↓
数据库主从 / 分库分表
↓
消息队列
↓
监控告警系统

十六、上线前检查清单

上线 Cloudflare 高并发配置前,建议逐项检查:

  • [ ] DNS 是否开启橙色云朵代理;
  • [ ] SSL/TLS 是否使用 Full 或 Full strict;
  • [ ] 源站是否部署有效 HTTPS 证书;
  • [ ] 静态资源是否正确缓存;
  • [ ] 后台、登录、用户中心是否绕过缓存;
  • [ ] API 是否区分公共接口和私有接口;
  • [ ] WAF 是否开启;
  • [ ] 登录、注册、搜索等接口是否限速;
  • [ ] 源站防火墙是否只允许 Cloudflare IP;
  • [ ] Nginx 是否获取真实客户端 IP;
  • [ ] 应用日志中 IP 是否正确;
  • [ ] 数据库慢查询是否优化;
  • [ ] Redis 是否缓存热点数据;
  • [ ] 是否有监控和告警;
  • [ ] 是否准备缓存清理方案。

十七、常见问题

1. 为什么开启 Cloudflare 后仍然很慢?

可能原因包括:

  • HTML 没有缓存;
  • 动态接口太慢;
  • 数据库慢查询;
  • 源站带宽不足;
  • Cloudflare 到源站链路不稳定;
  • 缓存命中率低;
  • 图片和静态资源没有优化。

可以在响应头中查看:

cf-cache-status: HIT
cf-cache-status: MISS
cf-cache-status: BYPASS
cf-cache-status: DYNAMIC

如果长期是 MISSDYNAMIC,说明请求仍然大量回源。

2. 后台登录异常怎么办?

一般是缓存规则配置错误。后台、登录、注册、用户中心、购物车、支付页面必须绕过缓存。

3. 如何清理缓存?

可以在 Cloudflare 后台执行 Purge Cache,也可以使用 API 清理指定 URL。

示例:

curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
  -H "Authorization: Bearer API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"files":["https://example.com/index.html"]}'

4. 是否应该开启 Always Online?

可以开启,但它不是高并发的核心方案。Always Online 更适合源站短暂不可用时展示缓存页面。

5. 是否应该开启 Brotli?

建议开启。Brotli 可以减少传输体积,提升页面加载速度,尤其适合文本资源。


十八、总结

Cloudflare 高并发解决方案的核心不是简单“套一层 CDN”,而是通过 缓存、限速、防护、源站隔离、应用优化 共同完成流量治理。

一套较为稳健的配置应包括:

  1. DNS 开启 Cloudflare 代理;
  2. SSL/TLS 使用 Full strict;
  3. 静态资源长期缓存;
  4. 公共 HTML 页面按需缓存;
  5. 私有页面和敏感接口绕过缓存;
  6. WAF 拦截恶意扫描;
  7. Rate Limiting 保护登录、注册、搜索、API;
  8. 源站防火墙只允许 Cloudflare IP;
  9. Nginx、PHP-FPM、Node.js 等源站服务进行高并发优化;
  10. Redis、数据库、队列等应用层配套优化。

如果配置得当,Cloudflare 可以将大量请求直接消化在全球边缘节点,使源站只处理真正必要的动态请求。对于大部分中小型业务而言,这是一套成本较低、落地简单、效果明显的高并发解决方案。

目录结构
全文