Git 整合部署
Git 整合部署是 Cloudflare Pages 最常用的方式:把 Pages 專案連接到 GitHub 或 GitLab 的儲存庫,每次推送程式碼,Cloudflare 就自動下載原始碼、執行建置指令,並把輸出目錄部署上線。生產分支(通常是 main)會更新正式網站,其他分支則產生預覽網址。
步驟一:建立 Pages 專案
- 在儀表板進入 Workers & Pages → Create → Pages,選擇 Import an existing Git repository。
- 第一次使用時授權 Cloudflare 存取 GitHub/GitLab,可以只授權特定儲存庫。
- 選擇要部署的儲存庫,按 Begin setup。
步驟二:設定建置參數
| 欄位 | 說明 | 範例 |
|---|---|---|
| Project name | 決定預設網址 專案名稱.pages.dev |
my-blog |
| Production branch | 正式網站對應的分支 | main |
| Framework preset | 選擇框架會自動帶入建置指令 | Astro、Vite、Next.js… |
| Build command | 建置指令 | npm run build |
| Build output directory | 建置後的輸出目錄 | dist |
| Root directory | 專案不在儲存庫根目錄時指定(monorepo) | apps/web |
常見框架的設定:
| 框架 | Build command | Output directory |
|---|---|---|
| 純 HTML(不需建置) | 留空 | / 或放網頁的目錄 |
| Vite/Vue/React (Vite) | npm run build |
dist |
| Astro | npm run build |
dist |
| Hugo | hugo |
public |
| MkDocs/Zensical | 見下方說明 | site |
部署 Python 文件網站(MkDocs/Zensical)
Pages 的建置環境內建 Python。在儲存庫根目錄放 requirements.txt 列出套件(例如 zensical),Build command 填 pip install -r requirements.txt && zensical build,Output directory 填 site。
步驟三:環境變數
在 Settings → Variables and Secrets 設定建置時需要的變數,例如:
NODE_VERSION = 22:指定 Node.js 版本。也可以在儲存庫放.nvmrc或.node-version檔案。PYTHON_VERSION = 3.12:指定 Python 版本。- API 金鑰等機密值請選 Secret 類型,儲存後無法再被讀出。
生產環境與預覽環境可以設定不同的變數值。
部署之後怎麼運作?
flowchart LR
A[git push main] --> B[Cloudflare 建置] --> C[更新 my-blog.pages.dev]
D[git push feature-x] --> E[Cloudflare 建置] --> F[feature-x.my-blog.pages.dev]
- 在 Deployments 頁可以看每次部署的建置紀錄與預覽網址。
- 部署出問題時,在舊的部署上選 Rollback to this deployment 即可秒速回到上一版,不用重新建置。
- 不想讓某些分支自動部署,可以在 Settings → Build → Branch control 設定只部署特定分支。
用 _redirects 與 _headers 控制行為
在輸出目錄放這兩個純文字檔,Pages 會自動套用:
單頁應用程式(SPA)若輸出目錄沒有 404.html,Pages 會自動把找不到的路徑導回 index.html,前端路由可以正常運作。