CDN工作原理深度解析
CDN是提升网站访问速度的最有效手段,理解原理才能用好它.
CDN请求流程
- 用户请求 img.example.com
- DNS返回CDN调度IP(而非源站IP)
- CDN节点检查缓存是否命中
- 命中: 直接返回缓存内容
- 未命中: 回源(去源站拉取),缓存后返回
CDN配置最佳实践
# Nginx配置缓存头
location ~* \.(jpg|png|gif|css|js)$ {
expires 30d;
add_header Cache-Control 'public, max-age=2592000';
add_header Vary Accept-Encoding;
}
# 动态内容不缓存
location /api/ {
add_header Cache-Control 'no-cache, no-store';
proxy_pass http://backend;
}
缓存刷新
# 阿里云CDN刷新缓存API
aliyun cdn RefreshObjectCaches \
--ObjectType File \
--ObjectPath 'https://cdn.example.com/static/app.js'
总结:静态资源上CDN是性价比最高的优化,命中率高则效果显著.
