cloudflare-pages

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Pages

Cloudflare Pages

Full-stack application hosting with Git-based or Direct Upload deployments to Cloudflare's global network.
基于Git或直接上传的方式,将全栈应用部署到Cloudflare全球网络的托管服务。

Quick Navigation

快速导航

  • Deployment methods →
    references/deployment.md
  • Build configuration →
    references/build.md
  • Pages Functions →
    references/functions.md
  • Bindings →
    references/bindings.md
  • Headers & Redirects →
    references/headers-redirects.md
  • Custom domains →
    references/domains.md
  • Wrangler CLI →
    references/wrangler.md
  • 部署方式 →
    references/deployment.md
  • 构建配置 →
    references/build.md
  • Pages Functions →
    references/functions.md
  • 绑定 →
    references/bindings.md
  • 标头与重定向 →
    references/headers-redirects.md
  • 自定义域名 →
    references/domains.md
  • Wrangler CLI →
    references/wrangler.md

When to Use

使用场景

  • Deploying static sites or JAMstack applications
  • Building full-stack apps with serverless functions
  • Configuring Git-based CI/CD deployments
  • Using Direct Upload for prebuilt assets
  • Setting up preview deployments for branches/PRs
  • Configuring custom domains and redirects
  • 部署静态站点或JAMstack应用
  • 构建包含无服务器函数的全栈应用
  • 配置基于Git的CI/CD部署
  • 使用直接上传部署预构建资源
  • 为分支/PR设置预览部署
  • 配置自定义域名和重定向

Deployment Methods

部署方式

MethodBest ForLimits
Git integrationCI/CD from GitHub/GitLabCannot switch to Direct Upload later
Direct UploadPrebuilt assets, CI pipelinesWrangler: 20k files, 25 MiB/file
C3 CLINew project scaffoldingFramework-dependent
方法最佳适用场景限制条件
Git集成来自GitHub/GitLab的CI/CD后续无法切换为直接上传方式
直接上传预构建资源、CI流水线Wrangler:最多20000个文件,单个文件最大25 MiB
C3 CLI新项目脚手架搭建依赖特定框架

Quick Deploy

快速部署

bash
undefined
bash
undefined

Create project

Create project

npx wrangler pages project create my-project
npx wrangler pages project create my-project

Deploy

Deploy

npx wrangler pages deploy ./dist
npx wrangler pages deploy ./dist

Preview deployment (branch)

Preview deployment (branch)

npx wrangler pages deploy ./dist --branch=feature-x
undefined
npx wrangler pages deploy ./dist --branch=feature-x
undefined

Build Configuration

构建配置

bash
undefined
bash
undefined

Framework presets (command → output directory)

Framework presets (command → output directory)

React (Vite): npm run build → dist

React (Vite): npm run build → dist

Next.js: npx @cloudflare/next-on-pages@1 → .vercel/output/static

Next.js: npx @cloudflare/next-on-pages@1 → .vercel/output/static

Nuxt.js: npm run build → dist

Nuxt.js: npm run build → dist

Astro: npm run build → dist

Astro: npm run build → dist

SvelteKit: npm run build → .svelte-kit/cloudflare

SvelteKit: npm run build → .svelte-kit/cloudflare

Hugo: hugo → public

Hugo: hugo → public

undefined
undefined

Environment Variables (build-time)

环境变量(构建时)

VariableValue
CF_PAGES
1
CF_PAGES_BRANCH
Branch name
CF_PAGES_COMMIT_SHA
Commit SHA
CF_PAGES_URL
Deployment URL
变量名取值
CF_PAGES
1
CF_PAGES_BRANCH
分支名称
CF_PAGES_COMMIT_SHA
提交SHA值
CF_PAGES_URL
部署URL

Pages Functions

Pages Functions

File-based routing in
/functions
directory:
/functions/index.js       → example.com/
/functions/api/users.js   → example.com/api/users
/functions/users/[id].js  → example.com/users/:id
javascript
// functions/api/hello.js
export function onRequest(context) {
  return new Response("Hello from Pages Function!");
}
/functions
目录中实现基于文件的路由:
/functions/index.js       → example.com/
/functions/api/users.js   → example.com/api/users
/functions/users/[id].js  → example.com/users/:id
javascript
// functions/api/hello.js
export function onRequest(context) {
  return new Response("Hello from Pages Function!");
}

Handler Types

处理器类型

ExportTrigger
onRequest
All methods
onRequestGet
GET only
onRequestPost
POST only
导出函数触发条件
onRequest
所有请求方法
onRequestGet
仅GET方法
onRequestPost
仅POST方法

Context Object

上下文对象

typescript
interface EventContext {
  request: Request;
  env: Env; // Bindings
  params: Params; // Route parameters
  waitUntil(promise: Promise<any>): void;
  next(): Promise<Response>;
  data: Record<string, any>;
}
typescript
interface EventContext {
  request: Request;
  env: Env; // Bindings
  params: Params; // Route parameters
  waitUntil(promise: Promise<any>): void;
  next(): Promise<Response>;
  data: Record<string, any>;
}

Bindings

绑定

Access Cloudflare resources via
context.env
:
BindingAccess Pattern
KV
context.env.MY_KV.get("key")
R2
context.env.MY_BUCKET.get("file")
D1
context.env.MY_DB.prepare("...").all()
Workers AI
context.env.AI.run(model, input)
For detailed binding configuration, see:
cloudflare-workers
skill.
通过
context.env
访问Cloudflare资源:
绑定类型访问方式
KV
context.env.MY_KV.get("key")
R2
context.env.MY_BUCKET.get("file")
D1
context.env.MY_DB.prepare("...").all()
Workers AI
context.env.AI.run(model, input)
有关绑定配置的详细信息,请查看:
cloudflare-workers
技能文档。

Headers & Redirects

标头与重定向

Create
_headers
and
_redirects
in build output directory.
txt
undefined
在构建输出目录中创建
_headers
_redirects
文件。
txt
undefined

_headers

_headers

/* X-Frame-Options: DENY /static/* Cache-Control: public, max-age=31536000, immutable

```txt
/* X-Frame-Options: DENY /static/* Cache-Control: public, max-age=31536000, immutable

```txt

_redirects

_redirects

/old-page /new-page 301 /blog/* https://blog.example.com/:splat

> **Warning:** `_headers` and `_redirects` do NOT apply to Pages Functions responses.
/old-page /new-page 301 /blog/* https://blog.example.com/:splat

> **注意:** `_headers`和`_redirects`不会应用于Pages Functions的响应。

Functions Invocation Routes

Functions调用路由

Control when Functions are invoked with
_routes.json
:
json
{
  "version": 1,
  "include": ["/api/*"],
  "exclude": ["/static/*"]
}
通过
_routes.json
控制Functions的触发时机:
json
{
  "version": 1,
  "include": ["/api/*"],
  "exclude": ["/static/*"]
}

Wrangler Configuration

Wrangler配置

jsonc
// wrangler.jsonc
{
  "name": "my-pages-app",
  "pages_build_output_dir": "./dist",
  "compatibility_date": "2024-01-01",
  "kv_namespaces": [{ "binding": "KV", "id": "<NAMESPACE_ID>" }],
  "d1_databases": [{ "binding": "DB", "database_name": "my-db", "database_id": "<ID>" }]
}
jsonc
// wrangler.jsonc
{
  "name": "my-pages-app",
  "pages_build_output_dir": "./dist",
  "compatibility_date": "2024-01-01",
  "kv_namespaces": [{ "binding": "KV", "id": "<NAMESPACE_ID>" }],
  "d1_databases": [{ "binding": "DB", "database_name": "my-db", "database_id": "<ID>" }]
}

Local Development

本地开发

bash
npx wrangler pages dev ./dist
bash
npx wrangler pages dev ./dist

With bindings

With bindings

npx wrangler pages dev ./dist --kv=MY_KV --d1=MY_DB=<ID>
undefined
npx wrangler pages dev ./dist --kv=MY_KV --d1=MY_DB=<ID>
undefined

Critical Prohibitions

重要注意事项

  • Do NOT expect
    _headers
    /
    _redirects
    to apply to Pages Functions responses — attach headers in code
  • Do NOT convert Direct Upload project to Git integration — not supported
  • Do NOT exceed redirect limits — 2,000 static + 100 dynamic redirects max
  • Do NOT use absolute URLs for proxying in
    _redirects
    — relative URLs only
  • Do NOT edit bindings in dashboard when using Wrangler config — file is source of truth
  • Do NOT store secrets in
    wrangler.toml
    — use dashboard or
    .dev.vars
    for local
  • 不要期望
    _headers
    /
    _redirects
    应用于Pages Functions的响应 — 需在代码中添加标头
  • 不要将直接上传项目转换为Git集成项目 — 该操作不被支持
  • 不要超过重定向限制 — 最多2000个静态重定向+100个动态重定向
  • 不要在
    _redirects
    中使用绝对URL进行代理 — 仅支持相对URL
  • 使用Wrangler配置时,不要在控制台编辑绑定 — 配置文件为唯一可信来源
  • 不要在
    wrangler.toml
    中存储密钥 — 本地使用控制台或
    .dev.vars

Common Gotchas

常见问题与解决方法

IssueSolution
Functions not invokedCheck
_routes.json
include/exclude patterns
Headers not appliedEnsure not a Functions response; attach in code
Build failsCheck build command exit code (must be 0)
Custom domain inactiveVerify DNS CNAME points to
<site>.pages.dev
Preview URLs indexedDefault
X-Robots-Tag: noindex
applied automatically
问题解决方法
Functions未被调用检查
_routes.json
中的包含/排除规则
标头未生效确认响应并非来自Functions;需在代码中添加标头
构建失败检查构建命令的退出码(必须为0)
自定义域名未激活验证DNS CNAME指向
<site>.pages.dev
预览URL被索引系统会自动添加默认的
X-Robots-Tag: noindex
标头

Quick Recipes

快速实践方案

Conditional Build Command

条件构建命令

bash
#!/bin/bash
if [ "$CF_PAGES_BRANCH" == "production" ]; then
  npm run build:prod
else
  npm run build:dev
fi
bash
#!/bin/bash
if [ "$CF_PAGES_BRANCH" == "production" ]; then
  npm run build:prod
else
  npm run build:dev
fi

SPA Fallback (404.html)

SPA回退页面(404.html)

Upload
404.html
in build output root for SPA routing.
在构建输出根目录上传
404.html
以支持SPA路由。

Disable Functions for Static Assets

为静态资源禁用Functions

json
// _routes.json
{
  "version": 1,
  "include": ["/api/*"],
  "exclude": ["/*"]
}
json
// _routes.json
{
  "version": 1,
  "include": ["/api/*"],
  "exclude": ["/*"]
}

Related Skills

相关技能

  • cloudflare-workers
    — Worker runtime, bindings API details
  • cloudflare-d1
    — D1 SQL database operations
  • cloudflare-r2
    — R2 object storage
  • cloudflare-kv
    — KV namespace operations
  • cloudflare-workers
    — Worker运行时、绑定API详细信息
  • cloudflare-d1
    — D1 SQL数据库操作
  • cloudflare-r2
    — R2对象存储
  • cloudflare-kv
    — KV命名空间操作