Astro 构建产物是纯静态文件,不需要 Worker 运行时逻辑。Cloudflare 现在推荐用 Workers Static Assets 托管,而不是单独开一个 Pages 项目。
目录
wrangler 配置
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "starlight-docs",
"compatibility_date": "2025-11-03",
"assets": {
"directory": "./dist",
"not_found_handling": "404-page"
},
"preview_urls": true
}
- 没有
main字段就是纯静态 Worker,只上传./dist。 not_found_handling: "404-page"会返回站点自带的404.html,并保留 404 状态码。- Astro 默认生成目录式路由(
/posts/tech/x/→dist/posts/tech/x/index.html),与 Cloudflare 默认的auto-trailing-slash行为一致。
本地验证与手动部署
npm run build
npx wrangler deploy --dry-run # 只校验配置和上传内容
npx wrangler dev # 用 Workers 运行时本地预览
npx wrangler deploy # 真正部署
当前主题的 build 脚本会额外执行 astro check、Pagefind 索引和索引复制,首次构建会比 Starlight 慢一些。
接入 Git 自动构建
Dashboard → Workers & Pages → Create application → Workers → Import a repository,连接仓库后填:
| 字段 | 值 |
|---|---|
| Root directory | / |
| Build command | npm run build |
| Deploy command | npx wrangler deploy |
| 环境变量 | NODE_VERSION = 22 |
主题还需要在 Workers Builds 里配置以下环境变量:
PUBLIC_SOCIAL_GITHUB=https://github.com/vps4128
PUBLIC_EDIT_POST_URL=https://github.com/vps4128/mynotebook/edit/main/
非生产分支的部署命令设为:
npx wrangler versions upload
这样 PR / feature 分支只会生成预览版本,main 分支才更新线上流量。构建凭据由 Cloudflare 自动注入,不需要手动配置 API Token。
自定义域名
在 wrangler.jsonc 里声明,跟随代码版本化:
"routes": [{ "pattern": "notebook.example.com", "custom_domain": true }]
域名需要已经托管在同一 Cloudflare 账号下,证书会自动签发。
踩坑
- 忘记 build:
wrangler deploy只上传./dist现有内容,部署脚本要串上astro build。 - 仓库里提交了
dist/:没必要,构建产物由 CI 生成。 - Node 版本漂移:Workers Builds 默认 Node 版本可能变化,显式设置
NODE_VERSION。 - SPA 回退:别把
not_found_handling设成single-page-application,那会让所有 404 都返回首页。 - 站点地图:
astro.config.ts里通过SITE.website设置站点地址,否则 sitemap 和 canonical 会不正确。 - 搜索索引:Pagefind 只在构建后生成,纯
npm run dev搜不到内容。