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

Cloudflare 扛高并发实战:从缓存、WAF 到源站加固的完整配置命令

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

Cloudflare 高并发解决方案|附完整命令

在互联网业务中,高并发往往意味着短时间内大量用户同时访问网站、接口或静态资源。对于中小型团队来说,如果仅依赖单台服务器硬扛流量,很容易出现 CPU 飙高、带宽打满、连接数耗尽、数据库被压垮等问题。

Cloudflare 作为全球知名的 CDN、安全防护和边缘网络平台,可以帮助我们将大量流量拦截、缓存、清洗和分发在边缘节点,从而显著降低源站压力。本文将从实际生产环境出发,介绍一套基于 Cloudflare + Nginx + Linux 系统优化 + 源站安全加固 的高并发解决方案,并附上完整命令和配置示例。


一、整体架构思路

高并发场景下,推荐架构如下:

用户
 ↓
Cloudflare 全球边缘节点
 ↓
Cloudflare CDN 缓存 / WAF / DDoS 防护 / 访问控制
 ↓
源站 Nginx
 ↓
应用服务 / 静态资源 / API
 ↓
数据库 / Redis / 对象存储

核心目标是:

  1. 静态资源尽量由 Cloudflare 缓存
  2. 恶意流量在 Cloudflare 层拦截
  3. 源站只允许 Cloudflare IP 访问
  4. Nginx 做连接数、缓存、压缩和反向代理优化
  5. Linux 系统提升最大连接数和网络吞吐能力
  6. 动态接口配合限流、缓存和负载均衡

二、Cloudflare 基础接入

1. 添加域名

登录 Cloudflare 控制台:

https://dash.cloudflare.com/

添加你的域名,例如:

example.com

Cloudflare 会扫描现有 DNS 记录,你需要确认 A 记录、CNAME 记录是否正确。

例如:

A     example.com       1.2.3.4
A     www               1.2.3.4
CNAME static            example.com

建议将需要经过 Cloudflare 代理的记录开启橙色云朵。


2. 修改域名 NS

Cloudflare 会给出两个 NS,例如:

arya.ns.cloudflare.com
todd.ns.cloudflare.com

到域名注册商后台,将原来的 NS 修改为 Cloudflare 提供的 NS。

等待 DNS 生效:

dig NS example.com

也可以查看解析结果:

dig A example.com

如果看到 Cloudflare 相关 IP,说明代理已经生效。


三、Cloudflare 推荐配置

1. SSL/TLS 配置

进入:

Cloudflare Dashboard → SSL/TLS → Overview

建议设置为:

Full 或 Full (strict)

生产环境推荐使用:

Full (strict)

这样 Cloudflare 到源站之间也会校验证书,安全性更高。


2. 开启 Always Use HTTPS

路径:

SSL/TLS → Edge Certificates

开启:

Always Use HTTPS

也可以开启:

Automatic HTTPS Rewrites

这样可以减少 HTTP 明文访问。


3. 开启 HTTP/2 和 HTTP/3

路径:

Speed → Optimization → Protocol Optimization

建议开启:

HTTP/2
HTTP/3 QUIC
0-RTT Connection Resumption

HTTP/2 和 HTTP/3 可以有效提升并发请求处理效率,特别适合资源较多的网站。


4. 缓存静态资源

路径:

Caching → Configuration

建议配置:

Browser Cache TTL: 1 month
Caching Level: Standard

如果是静态资源域名,例如:

static.example.com

可以配置更激进的缓存策略。


5. Page Rules 缓存静态文件

进入:

Rules → Page Rules

添加规则:

URL:
https://static.example.com/*

设置:
Cache Level: Cache Everything
Edge Cache TTL: a month
Browser Cache TTL: a month

如果静态资源文件名带 hash,例如:

app.8f3a1c.js
style.9ad31.css

可以放心设置长期缓存。


6. Cache Rules 示例

新版 Cloudflare 推荐使用 Cache Rules。

路径:

Rules → Cache Rules

创建规则:

If:
Hostname equals static.example.com

Then:
Cache eligibility: Eligible for cache
Edge TTL: 1 month
Browser TTL: 1 month

对于图片、CSS、JS,可以进一步匹配路径:

URI Path ends with .jpg
URI Path ends with .png
URI Path ends with .webp
URI Path ends with .css
URI Path ends with .js

四、源站安装 Nginx

以下以 Ubuntu 22.04 为例。

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装 Nginx

sudo apt install nginx -y

查看版本:

nginx -v

启动并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

查看状态:

sudo systemctl status nginx

五、申请源站 HTTPS 证书

如果使用 Cloudflare 的 Full (strict),源站必须有有效证书。

可以使用 Cloudflare Origin Certificate,也可以使用 Let's Encrypt。

这里以 Let's Encrypt 为例。

1. 安装 Certbot

sudo apt install certbot python3-certbot-nginx -y

2. 申请证书

sudo certbot --nginx -d example.com -d www.example.com

按提示选择自动配置 HTTPS。

3. 测试自动续期

sudo certbot renew --dry-run

六、Nginx 高并发优化配置

1. 修改 Nginx 主配置

编辑配置文件:

sudo vim /etc/nginx/nginx.conf

推荐配置如下:

user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;

pid /run/nginx.pid;

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

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    keepalive_timeout 30;
    keepalive_requests 10000;

    types_hash_max_size 2048;
    server_tokens off;

    client_max_body_size 50m;
    client_body_buffer_size 128k;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

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

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

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

    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_req_zone $binary_remote_addr zone=req_limit_perip:10m rate=20r/s;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

检查配置:

sudo nginx -t

重载 Nginx:

sudo systemctl reload nginx

七、Nginx 站点配置示例

编辑站点配置:

sudo vim /etc/nginx/sites-available/example.com

写入以下内容:

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.com;
    index index.html index.htm;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    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 X-XSS-Protection "1; mode=block" always;

    limit_conn perip 50;
    limit_req zone=req_limit_perip burst=40 nodelay;

    location / {
        try_files $uri $uri/ /index.html;
    }

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

    location ~* \.(html)$ {
        expires 5m;
        add_header Cache-Control "public, max-age=300";
    }
}

创建软链接:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com

创建网站目录:

sudo mkdir -p /var/www/example.com
sudo chown -R www-data:www-data /var/www/example.com

写入测试文件:

echo "Hello Cloudflare High Concurrency" | sudo tee /var/www/example.com/index.html

检查配置并重载:

sudo nginx -t
sudo systemctl reload nginx

八、反向代理应用服务配置

如果你的后端应用运行在本地端口,例如:

127.0.0.1:3000

可以配置 Nginx 反向代理。

sudo vim /etc/nginx/sites-available/api.example.com

配置如下:

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

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

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

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

    ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;

    client_max_body_size 20m;

    limit_conn perip 30;
    limit_req zone=req_limit_perip burst=30 nodelay;

    location / {
        proxy_pass http://backend_app;

        proxy_http_version 1.1;
        proxy_set_header Connection "";

        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 X-Forwarded-Proto $scheme;

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

        proxy_buffering on;
        proxy_buffer_size 16k;
        proxy_buffers 16 16k;
        proxy_busy_buffers_size 64k;
    }
}

启用配置:

sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled/api.example.com
sudo nginx -t
sudo systemctl reload nginx

九、Linux 系统高并发优化

1. 修改文件句柄限制

编辑:

sudo vim /etc/security/limits.conf

添加:

* soft nofile 65535
* hard nofile 65535
www-data soft nofile 65535
www-data hard nofile 65535
root soft nofile 65535
root hard nofile 65535

2. 修改 systemd 限制

创建 Nginx override 配置:

sudo mkdir -p /etc/systemd/system/nginx.service.d
sudo vim /etc/systemd/system/nginx.service.d/override.conf

写入:

[Service]
LimitNOFILE=65535

重新加载 systemd:

sudo systemctl daemon-reload
sudo systemctl restart nginx

查看是否生效:

cat /proc/$(pidof nginx | awk '{print $1}')/limits | grep "Max open files"

3. 内核网络参数优化

编辑:

sudo vim /etc/sysctl.conf

添加以下内容:

net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535

net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_tw_reuse = 1

net.ipv4.ip_local_port_range = 1024 65535

net.ipv4.tcp_syncookies = 1

net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216

应用配置:

sudo sysctl -p

查看参数:

sysctl net.core.somaxconn
sysctl net.ipv4.tcp_max_syn_backlog
sysctl net.ipv4.tcp_fin_timeout

十、只允许 Cloudflare 访问源站

这是非常关键的一步。如果源站 IP 暴露,攻击者可能绕过 Cloudflare 直接打源站。

1. 获取 Cloudflare IP 段

IPv4:

curl -s https://www.cloudflare.com/ips-v4

IPv6:

curl -s https://www.cloudflare.com/ips-v6

2. 使用 UFW 放行 Cloudflare

安装 UFW:

sudo apt install ufw -y

允许 SSH,避免锁死服务器:

sudo ufw allow 22/tcp

允许 Cloudflare IPv4:

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:

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 default deny incoming
sudo ufw default allow outgoing

启用 UFW:

sudo ufw enable

查看状态:

sudo ufw status numbered

十一、恢复真实客户端 IP

经过 Cloudflare 后,Nginx 默认看到的访问 IP 通常是 Cloudflare 节点 IP。为了日志、限流和安全分析,需要恢复真实 IP。

编辑 Nginx 配置:

sudo vim /etc/nginx/conf.d/cloudflare-real-ip.conf

写入 Cloudflare 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;

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 WAF 与限流策略

1. 开启 WAF

路径:

Security → WAF

建议开启:

Managed Rules
Cloudflare Managed Ruleset
OWASP Core Ruleset

对于 WordPress、Laravel、Node.js API 等应用,可以根据业务开启对应规则。


2. 防止恶意请求接口

例如登录接口:

/api/login

可以配置 WAF 自定义规则:

If:
URI Path equals /api/login

Then:
Managed Challenge

也可以针对国家、ASN、User-Agent 等规则做限制。


3. Rate Limiting

路径:

Security → WAF → Rate limiting rules

示例规则:

If:
URI Path starts with /api/

Rate:
100 requests per 10 seconds

Action:
Managed Challenge 或 Block

对于登录接口建议更严格:

URI Path equals /api/login
10 requests per 1 minute
Action: Managed Challenge

这样可以在 Cloudflare 边缘层拦截大量暴力请求。


十三、Cloudflare 缓存 API 的注意事项

不是所有接口都适合缓存。一般来说:

适合缓存:

GET /api/articles
GET /api/products
GET /api/categories
GET /api/config

不适合缓存:

POST /api/login
POST /api/order
GET /api/user/profile
GET /api/cart

如果要缓存公开 GET API,建议接口返回明确缓存头:

Cache-Control: public, max-age=60

Nginx 中也可以添加:

location /api/public/ {
    proxy_pass http://backend_app;
    proxy_cache_valid 200 1m;
    add_header Cache-Control "public, max-age=60";
}

但如果你使用 Cloudflare 缓存动态接口,一定要避免缓存用户私有数据。


十四、使用 Cloudflare Workers 做边缘处理

在高并发场景下,部分简单逻辑可以放到 Cloudflare Workers 上执行,例如:

  1. 简单重定向
  2. A/B 测试
  3. Header 注入
  4. 基础鉴权
  5. 静态 JSON 返回
  6. 简单 API 聚合

示例 Worker:

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

    if (url.pathname === "/health") {
      return new Response(JSON.stringify({
        status: "ok",
        edge: true
      }), {
        headers: {
          "Content-Type": "application/json",
          "Cache-Control": "public, max-age=10"
        }
      })
    }

    return fetch(request)
  }
}

这样 /health 请求可以直接由边缘节点响应,不打到源站。


十五、压测验证

在优化完成后,可以使用压测工具验证效果。

1. 安装 wrk

Ubuntu 安装:

sudo apt install build-essential git -y
git clone https://github.com/wg/wrk.git
cd wrk
make
sudo cp wrk /usr/local/bin/

查看版本:

wrk -v

2. 压测静态页面

wrk -t4 -c400 -d30s https://example.com/

参数说明:

-t4    4 个线程
-c400  400 个并发连接
-d30s  持续 30 秒

3. 压测 API

wrk -t8 -c800 -d60s https://api.example.com/api/products

如果 Cloudflare 缓存命中率高,源站压力会明显降低。


十六、查看 Cloudflare 缓存是否命中

使用 curl 查看响应头:

curl -I https://example.com/static/app.js

重点查看:

CF-Cache-Status: HIT

常见状态:

HIT       命中缓存
MISS      未命中缓存
BYPASS    绕过缓存
DYNAMIC   动态请求,未缓存
EXPIRED   缓存过期后重新回源

如果静态资源长期显示 MISSDYNAMIC,说明缓存规则需要调整。


十七、常见问题与解决方案

1. 源站 CPU 仍然很高

可能原因:

  1. 动态接口未缓存
  2. 数据库查询过慢
  3. WAF 和限流规则过于宽松
  4. 静态资源没有走 Cloudflare 缓存
  5. 攻击者绕过 Cloudflare 直接访问源站 IP

解决方式:

top
htop
iostat
free -h
ss -ant | wc -l

查看 Nginx 连接:

ss -antp | grep nginx | wc -l

查看访问日志:

sudo tail -f /var/log/nginx/access.log

2. 真实 IP 获取失败

检查是否配置:

real_ip_header CF-Connecting-IP;

检查 Cloudflare IP 段是否完整。

查看日志中的 IP:

sudo tail -n 20 /var/log/nginx/access.log

3. Cloudflare 缓存不生效

检查响应头:

curl -I https://example.com/path/to/file.js

如果看到:

Cache-Control: no-cache
Cache-Control: private

Cloudflare 通常不会缓存。

可以在 Nginx 中调整:

location ~* \.(css|js|jpg|jpeg|png|webp|svg|woff2?)$ {
    expires 30d;
    add_header Cache-Control "public, max-age=2592000, immutable";
}

4. 访问出现 522

Cloudflare 522 通常表示连接源站超时。

排查命令:

sudo systemctl status nginx
sudo nginx -t
curl -I http://127.0.0.1
ss -lntp

检查防火墙是否误拦截 Cloudflare:

sudo ufw status

5. 访问出现 521

521 通常表示源站拒绝连接,可能是 Nginx 未启动或端口未监听。

sudo systemctl restart nginx
sudo systemctl status nginx
ss -lntp | grep nginx

十八、推荐生产环境策略

一套比较稳妥的生产环境策略如下:

1. DNS 走 Cloudflare 橙色云代理
2. SSL 使用 Full (strict)
3. 静态资源使用独立域名 static.example.com
4. 静态资源文件名带 hash,并设置长期缓存
5. API 接口按路径配置限流
6. 登录、注册、支付接口开启 WAF Challenge
7. 源站防火墙只允许 Cloudflare IP 访问 80/443
8. Nginx 开启 gzip、open_file_cache、keepalive
9. Linux 调整 nofile、somaxconn、tcp backlog
10. 数据库前增加 Redis 缓存
11. 使用对象存储承载大文件
12. 定期查看 Cloudflare Analytics 和 Nginx 日志

十九、一键更新 Cloudflare IP 防火墙脚本

Cloudflare IP 段偶尔会变化,建议写脚本定期更新。

创建脚本:

sudo vim /usr/local/bin/update-cloudflare-ufw.sh

写入:

#!/bin/bash

set -e

echo "Reset UFW rules..."
ufw --force reset

echo "Allow SSH..."
ufw allow 22/tcp

echo "Allow Cloudflare IPv4..."
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
  ufw allow from "$ip" to any port 80 proto tcp
  ufw allow from "$ip" to any port 443 proto tcp
done

echo "Allow Cloudflare IPv6..."
for ip in $(curl -s https://www.cloudflare.com/ips-v6); do
  ufw allow from "$ip" to any port 80 proto tcp
  ufw allow from "$ip" to any port 443 proto tcp
done

echo "Set default policy..."
ufw default deny incoming
ufw default allow outgoing

echo "Enable UFW..."
ufw --force enable

echo "Done."
ufw status

赋予执行权限:

sudo chmod +x /usr/local/bin/update-cloudflare-ufw.sh

执行:

sudo /usr/local/bin/update-cloudflare-ufw.sh

添加定时任务:

sudo crontab -e

加入:

0 3 * * 1 /usr/local/bin/update-cloudflare-ufw.sh >/var/log/update-cloudflare-ufw.log 2>&1

表示每周一凌晨 3 点自动更新 Cloudflare IP 防火墙规则。


二十、总结

Cloudflare 并不是简单的 CDN,它更像是业务入口层的全球边缘网关。面对高并发场景,正确使用 Cloudflare 可以让大量静态请求、恶意请求和异常流量在边缘节点就被处理掉,从而保护源站稳定运行。

一套成熟的 Cloudflare 高并发方案,至少应该包含:

Cloudflare CDN 缓存
Cloudflare WAF 防护
Cloudflare Rate Limiting
源站 HTTPS
源站只允许 Cloudflare IP
Nginx 高并发优化
Linux 网络参数优化
真实 IP 恢复
日志监控与压测验证

如果你的业务主要是静态网站、前端资源、文档站、图片站或公开内容接口,Cloudflare 的缓存能力可以带来非常明显的性能提升。如果你的业务以动态接口、登录态和交易系统为主,则需要配合 Redis、数据库优化、接口限流、负载均衡和后端水平扩容,才能真正支撑大规模并发。

最终原则很简单:能在 Cloudflare 边缘处理的,不要打到源站;能缓存的,不要重复计算;能限流的,不要无限放行;能隐藏源站的,绝不暴露真实 IP。

目录结构
全文