Skip to content
返回部署

CDN 缓存策略

配置 CDN 缓存头和清除策略,实现最佳内容交付。

边缘进阶

为什么

正确的 CDN 缓存可减少源站负载 90%+,并全球改善 TTFB。Cloudflare 边缘网络覆盖 330+ 城市,全球 p95 延迟低于 50ms。

边缘函数相比源服务器将 TTFB 降低 60-80%,Akamai 报告 2024 年 40% 的企业使用边缘计算。

何时使用

任何有全球受众或大量静态资源的站点。 需要数据库写入的有状态逻辑避免边缘函数 — 边缘运行时无持久连接池。需要长时间运行任务(>30s)或重 CPU 计算时跳过。

如何做

# 缓存 头s in next.配置.js async headers() { return [ { source: '/_next/static/:path*', headers: [ { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' } ] }, { source: '/images/:path*', headers: [ { key: 'Cache-Control', value: 'public, max-age=86400, s-maxage=2592000' } ] } ]; } # Purge 缓存 on 部署 curl -X POST "https://api.vercel.com/v2/deployments/$DEPLOY_ID/files" \ -H "Authorization: Bearer $TOKEN" 4. 验证部署 — curl -I https://your-app.example.com 5. 监控日志 — 前 5 分钟检查错误 6. 需要时回滚 — 回退到上一版本

示例

// 配置 — deploy-cdn-cache const config = require("./config"); # Cloudflare 缓存 规则s (Page 规则s) URL: example.com/api/* Cache Level: Bypass Cache URL: example.com/_next/static/* Cache Level: Cache Everything Edge Cache TTL: 1 year

常见问题

  • ⚠缓存未清除 — 用 vercel purge 或 Cloudflare API
  • ⚠动态内容过度缓存 — 用 s-maxage 配合 revalidation
  • ⚠环境间配置漂移 — 使用基础设施即代码(Terraform/Pulumi)保持 dev/staging/prod 一致

最佳实践

  • ✓哈希资源用 immutable — 长缓存无需 revalidation
  • ✓用 stale-while-revalidate — 取新时先返回旧
  • ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求

常见问题解答