一、CDN 的核心价值
CDN(Content Delivery Network,内容分发网络)通过在全球范围内部署边缘节点,将用户请求路由到地理距离最近的节点,从而大幅降低延迟、减轻源站压力。
加速效果对比(源站位于中国香港,实测数据):
| 访问来源 | 直连源站 | CDN 加速后 | 延迟降低 |
|---|---|---|---|
| 新加坡 | 380ms | 45ms | ↓ 88% |
| 东京 | 420ms | 45ms | ↓ 89% |
| 伦敦 | 580ms | 10ms | ↓ 98% |
| 圣保罗 | 650ms | 8ms | ↓ 99% |
二、DNS 配置与 CNAME 接入
# DNS 记录配置示例(以 Cloudflare 为例)
# 类型 名称 内容 TTL 代理状态
# A @ 源站服务器 IP 自动 关闭(先验证)
# CNAME www example.cdn.cloudflare.net 自动 开启(橙色云朵)
# 验证源站可达后再开启 CDN 代理
三、Nginx 源站缓存头配置
# 静态资源 — 长时间缓存
location ~* \.(jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
add_header X-Content-Type-Options "nosniff";
}
# CSS / JS — 带版本号的长期缓存
location ~* \.(css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
# HTML — 短期缓存或协商缓存
location / {
expires 10m;
add_header Cache-Control "public, must-revalidate";
add_header Vary "Accept-Encoding";
}
# API 接口 — 禁止缓存
location /api/ {
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header Pragma "no-cache";
add_header Expires "0";
}
四、CDN 边缘缓存策略
# Cloudflare Page Rules 示例
# 1. 全站缓存级别:Standard
# 2. 静态资源缓存
# URL: example.com/static/*
# Cache Level: Cache Everything
# Edge Cache TTL: 30 days
#
# 3. API 不缓存
# URL: example.com/api/*
# Cache Level: Bypass
#
# 4. 管理后台不缓存
# URL: example.com/admin/*
# Cache Level: Bypass
# Disable Security: 关闭
# Disable Performance: 关闭
五、缓存命中率验证
# 使用 curl 检查缓存头
curl -I https://example.com/static/logo.png
# 期望响应头:
HTTP/2 200
cf-cache-status: HIT # ← Cloudflare 命中
cache-control: public, max-age=31536000
age: 86400 # 已在 CDN 缓存了 24 小时
x-cache: HIT # ← 其他 CDN 的命中标记
# MISS 表示未命中,需要回源
# HIT 表示命中边缘缓存
# EXPIRED 表示缓存已过期,回源后更新
六、预热与刷新
# 手动预热热门资源(大批量更新前)
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/purge" \
-H "Authorization: Bearer {api_token}" \
-H "Content-Type: application/json" \
--data '{"files":[
"https://example.com/static/main.js",
"https://example.com/static/style.css"
]}'
# 全站刷新(⚠️ 谨慎使用,会瞬间大量回源)
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/cache/purge" \
-H "Authorization: Bearer {api_token}" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}'
💡 CDN 加速核心原则
静态资源使用内容哈希命名(main.v1a2b3c.js),实现永久缓存;HTML 页面使用短 TTL + CDN 边缘重验证;API 数据严格禁止缓存。监控 cf-cache-status 命中率,目标保持在 85% 以上。