本教程将指导您如何配置源站规则和 DNS 记录,以自定义域名指向 Pages 部署。
本流程将使用以下示例值:
| 网站访问者将访问的 URL | mycustomerexample.com/blog/* |
| Zone 域名 | mycustomerexample.com |
| Cloudflare Pages 子域名 | myblog.pages.dev |
| Cloudflare Pages 自定义域名 | blogmirror.example.com |
配置 Pages 自定义域名时,请使用您不打算在生产中使用的自定义域名(本例中为 blogmirror.example.com)。
要将自定义域名添加到 Pages 部署:
-
在 Cloudflare 仪表板中,前往 Workers & Pages 页面。
Go to Workers & Pages ↗ -
选择您的 Pages 项目。
-
前往 Custom domains(自定义域名)。
-
选择 Set up a custom domain(设置自定义域名)。
-
输入
blogmirror.example.com并选择 Continue(继续)。
将自定义域名添加到 Pages 部署时,Cloudflare 会自动为该自定义域名创建 CNAME DNS 记录。
在您的 mycustomerexample.com zone 中,创建具有以下配置的源站规则:
If incoming requests match(如果传入请求匹配)
| Field(字段) | Operator(运算符) | Value(值) |
|---|---|---|
| URI Path | wildcard | /blog/* |
若使用 Expression Editor,请输入以下表达式:
(http.request.uri.path wildcard "/blog/*")Set origin parameters(设置源站参数)
- Host header(主机标头) > Rewrite to(重写为) 之后的值:
blogmirror.example.com - DNS record(DNS 记录) > Override to(覆盖为) 之后的值:
blogmirror.example.com
在此示例中,网站访问者访问的 URL 以 /blog 开头。但是,Pages 部署没有此初始 URL 段。
使用 URL 改写从 URL 路径中移除 /blog 段。
-
前往 Rules > Overview(概览)。
-
选择 Create rule(创建规则) > URL Rewrite Rule(URL 重写规则)。
-
在 Rule name(规则名称) 中输入规则的描述性名称。
-
在 If incoming requests match(如果传入请求匹配) 中,选择 Wildcard pattern(通配符模式)。
-
在 Request URL(请求 URL) 中输入以下值:
https://<YOUR_HOSTNAME>/blog/*在当前示例中,该值为
https://mycustomerexample.com/blog/*。 -
在 Then rewrite the path and/or query(然后重写路径和/或查询) 中,在 Path(路径) 下输入以下值:
Target path Rewrite to [ /]blog/*[ /]${1} -
选择 Deploy(部署)。