重定向和重写
在边缘配置 URL 重定向和重写,用于 SEO 和迁移。
边缘入门
为什么
边缘重定向保留 SEO 权重,处理域名迁移无需源站往返。Cloudflare 边缘网络覆盖 330+ 城市,全球 p95 延迟低于 50ms。
边缘函数相比源服务器将 TTFB 降低 60-80%,Akamai 报告 2024 年 40% 的企业使用边缘计算。
何时使用
域名迁移、URL 重构或旧 URL 支持。 需要数据库写入的有状态逻辑避免边缘函数 — 边缘运行时无持久连接池。需要长时间运行任务(>30s)或重 CPU 计算时跳过。
如何做
# next.配置.js 重定向s and 重写s
module.exports = {
async redirects() {
return [
{ source: '/old-blog/:slug', destination: '/blog/:slug', permanent: true },
{ source: '/docs', destination: '/documentation', permanent: false },
];
},
async rewrites() {
return [
{ source: '/api/v1/:path*', destination: 'https://api.example.com/v1/:path*' },
{ source: '/proxy/:path*', destination: '/api/:path*' },
];
},
};
4. 验证部署 — curl -I https://your-app.example.com
5. 监控日志 — 前 5 分钟检查错误
6. 需要时回滚 — 回退到上一版本
示例
# Vercel.JSON 重定向s
{
"redirects": [
{ "source": "/old", "destination": "/new", "permanent": true },
{ "source": "/external", "destination": "https://example.com", "permanent": false }
],
"rewrites": [
{ "source": "/(.*)", "destination": "/index.html" }
]
}
常见问题
- ⚠重定向循环 — 检查源/目标不重叠
- ⚠重写不工作 — 验证目标可达
- ⚠环境间配置漂移 — 使用基础设施即代码(Terraform/Pulumi)保持 dev/staging/prod 一致
最佳实践
- ✓永久移动用 301 — 保留 SEO
- ✓API 代理用重写 — 避免 CORS 问题
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求