跳到主要内容

最佳实践

本章总结 Cloudflare 在生产环境中的最佳实践,帮助你构建安全、高性能、可靠的网站和应用。

安全最佳实践​

SSL/TLS 配置​

推荐配置:

  1. SSL 模式:Full (Strict)
  2. 启用 Always Use HTTPS
  3. 启用 HSTS(至少 6 个月)
  4. 启用 TLS 1.3
  5. 最低 TLS 版本:TLS 1.2

配置步骤:

SSL/TLS → Overview → Full (Strict)
SSL/TLS → Edge Certificates → Always Use HTTPS: On
SSL/TLS → Edge Certificates → HSTS: Enable
SSL/TLS → Edge Certificates → TLS 1.3: On
SSL/TLS → Edge Certificates → Minimum TLS Version: TLS 1.2

WAF 配置​

推荐配置:

  1. 启用 OWASP Core Ruleset
  2. 设置 Paranoia Level 2
  3. 配置速率限制规则
  4. 启用 Bot Fight Mode

关键规则:

# 保护登录接口
URI Path contains "/login" → Rate Limit: 10/min

# 保护 API
URI Path starts with "/api/" → Rate Limit: 100/min

# 阻止已知攻击 IP
IP in list [blocked_ips] → Block

访问控制​

敏感路径保护:

# 管理后台
URI Path starts with "/admin" → Block (或 Challenge)

# 敏感 API
URI Path starts with "/api/admin" → Block (或 Challenge)

安全响应头​

创建 _headers 文件:

/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=(), camera=()
Content-Security-Policy: default-src 'self'

性能最佳实践​

缓存策略​

静态资源:

URL 匹配: /static/* 或 /assets/*
Cache Level: Cache Everything
Edge TTL: 1 month
Browser TTL: 1 year

动态内容:

URL 匹配: /api/*
Cache Level: Bypass

HTML 页面:

URL 匹配: /*
Cache Level: Standard
Edge TTL: 4 hours
Browser TTL: 1 hour

性能优化​

启用功能:

Speed → Optimization:
- Auto Minify: HTML, CSS, JS 全部启用
- Brotli: On
- Early Hints: On
- Rocket Loader: On (测试后)

图片优化:

Speed → Optimization:
- Polish: Lossy
- WebP: On
- Mirage: On

HTTP/3​

启用最新协议:

Network → HTTP/3 (with QUIC): On

DNS 最佳实践​

记录配置​

网站记录:

类型: A
名称: @
内容: 服务器 IP
代理: 开启(橙色云朵)

类型: A
名称: www
内容: 服务器 IP
代理: 开启

邮件记录:

类型: MX
名称: @
内容: mail.example.com
优先级: 10
代理: 关闭(灰色云朵)

类型: TXT
名称: @
内容: v=spf1 include:_spf.google.com ~all
代理: 关闭

DNSSEC​

启用 DNSSEC 防止 DNS 劫持:

DNS → Settings → DNSSEC: Enable

Workers 最佳实践​

代码优化​

使用 Hono 框架:

import { Hono } from 'hono';

const app = new Hono();

app.get('/api/users/:id', async (c) => {
const id = c.req.param('id');
const user = await c.env.DB.prepare(
'SELECT * FROM users WHERE id = ?'
).bind(id).first();

return c.json(user);
});

export default app;

错误处理:

app.get('/api/users/:id', async (c) => {
try {
const id = c.req.param('id');
const user = await getUser(c.env, id);

if (!user) {
return c.json({ error: 'Not Found' }, 404);
}

return c.json(user);
} catch (error) {
console.error('Error:', error);
return c.json({ error: 'Internal Server Error' }, 500);
}
});

环境变量​

敏感信息使用 Secrets:

wrangler secret put API_KEY

非敏感信息使用 vars:

[vars]
ENVIRONMENT = "production"

CORS 处理​

const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};

app.use('*', async (c, next) => {
if (c.req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
await next();
c.res.headers.set('Access-Control-Allow-Origin', '*');
});

Pages 最佳实践​

构建配置​

环境变量:

NODE_VERSION=20
BUILD_COMMAND=npm run build
OUTPUT_DIR=dist

SPA 路由:

创建 _redirects 文件:

/* /index.html 200

Functions​

API 结构:

functions/
├── api/
│ ├── users.ts
│ └── posts.ts
└── _middleware.ts

中间件:

export async function onRequest(context) {
const { request, next } = context;

// 添加 CORS 头
const response = await next();
response.headers.set('Access-Control-Allow-Origin', '*');

return response;
}

监控与告警​

设置告警​

关键告警:

Notifications → Add:
- DDoS Attack Alert
- HTTP Error Rate Alert
- Origin Unreachable Alert

日志分析​

启用 Logpush(付费):

Analytics → Logs → Logpush

推送到:

  • S3
  • Google Cloud Storage
  • Datadog
  • Splunk

成本优化​

免费计划优化​

合理使用免费额度:

服务免费额度优化建议
Workers10 万请求/天使用缓存减少请求
Pages500 构建/月合并部署
R210GB 存储定期清理
D15GB 存储归档旧数据
KV1GB 存储设置过期时间

缓存优化​

减少 Workers 请求:

export default {
async fetch(request, env, ctx) {
const cache = caches.default;
const cached = await cache.match(request);

if (cached) {
return cached;
}

const response = await fetchAndProcess(request);
ctx.waitUntil(cache.put(request, response.clone()));

return response;
},
};

故障排查​

常见问题​

502 Bad Gateway:

  1. 检查源服务器是否运行
  2. 检查 SSL 模式是否正确
  3. 检查防火墙是否阻止 Cloudflare IP

504 Gateway Timeout:

  1. 检查源服务器响应时间
  2. 优化数据库查询
  3. 考虑使用 Workers 处理

SSL 证书错误:

  1. 检查 SSL 模式设置
  2. 确认源服务器证书有效
  3. 检查证书链是否完整

调试工具​

检查 DNS:

dig example.com
nslookup example.com

检查 SSL:

curl -vI https://example.com
openssl s_client -connect example.com:443

检查响应头:

curl -I https://example.com

迁移清单​

新站点上线清单​

  • DNS 记录配置正确
  • SSL 模式设置为 Full (Strict)
  • 启用 Always Use HTTPS
  • 配置 WAF 规则
  • 设置速率限制
  • 配置缓存规则
  • 启用性能优化
  • 设置告警通知
  • 测试所有功能

从其他平台迁移​

  • 导出 DNS 记录
  • 配置 SSL 证书
  • 设置页面规则
  • 配置重定向
  • 测试网站功能
  • 更新 NS 记录
  • 监控迁移状态

参考链接​

下一步​

完成最佳实践学习后,可以查看 速查表,获取常用命令和配置速查。