[笔记] · · 1 分钟
Cloudflare Pages 部署实践笔记
从 GitHub 推送到边缘节点的整条链路。我们怎么配 _headers、_redirects、缓存策略,以及 SSR Worker 的边界。
cloudflaredeploymentcdn
站点跑在边缘,不是跑在某个机房。
我们没踩的坑(因为没用)
- 没买服务器
- 没装 nginx
- 没写 systemd unit
- 没配 fail2ban
- 没盯磁盘
Cloudflare Pages 自动从 GitHub 拉代码 → 跑 pnpm build → 推到全球 300+ 边缘节点。每次 git push main 就是一次部署。
_headers:缓存策略
/_astro/*
Cache-Control: public, max-age=31536000, immutable
/assets/*
Cache-Control: public, max-age=31536000, immutable
/*
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
/_astro/* 是 Astro 哈希过的资源,永不过期;HTML 走 must-revalidate,改完 push 立刻生效。
_redirects:少即是多
/*/ /:splat 301
只做了一件事:把 /foo/ 跳到 /foo。其余的重定向都通过 Astro 的 routing 完成——没必要让 CDN 多一跳。
Security headers
X-Content-Type-Options: nosniff:阻止 MIME 嗅探Referrer-Policy: strict-origin-when-cross-origin:referer 只发同源 hostStrict-Transport-Security:强制 HTTPSPermissions-Policy: camera=(), microphone=(), geolocation=():默认关掉所有用不上的设备 API
CSP 我没加。对静态站来说,CSP 主要防的是 XSS,但静态站没用户输入。 真要加,可以用 Content-Security-Policy: default-src 'self',再按需放开。
当我们想要 SSR 时
Cloudflare Pages 自带 Functions(基于 Workers)。我们目前完全没用,但接口已经留好:
// functions/api/now.ts
export const onRequest = async () =>
new Response(JSON.stringify({ ok: true, ts: Date.now() }), {
headers: { 'content-type': 'application/json' },
});
/api/now 就会变成一个 Worker。如果哪天 Hero 想接实时数据,这就是入口。
部署时间
| 阶段 | 时长 |
|---|---|
pnpm install | ~25s(cache 命中后 ~5s) |
astro build | ~3s(10 个页面) |
| Cloudflare 边缘推送 | ~10s |
总计从 git push 到全球可见:30 秒左右。
没有比这更便宜的「部署到生产」了。