我在阿里云万网购买的个人域名
zshell.cc
, 原先 CNAME 到了 github pages 的域名, 由于地缘政治风险, 已无法通畅访问, 于是我将博客迁移到了国内的 开放原子 atomgit pages, 本文记录了我如何利用 cloudflare 将域名解析完美迁移到 atomgit 的过程;
国内域名托管商的限制
我的需求如下:
- 我想让用户使用 zshell.cc 域名访问我的博客, 同时不能重定向到 atomgit 给我分配的默认域名 zshellzhang.atomgit.net;
- atomgit pages 首页限制了必须要带上默认的 path (值为注册在 atomgit 的仓库名, 我的是 zshell), 那么当我访问 zshell.cc, 需要帮我重定向到 zshell.cc/zshell;
对此需求, 普通的 CNAME 解析已经不够用了, 必须使用隐式 URI 解析, 另外还存在当匹配部分 path 时替换为指定 path 的场景, 这已经属于比较高级的需求了;
原先我的域名解析托管在阿里云万网, 然而万网对于配置 URI 解析的前提是要求域名必须在国内备案, 而备案又要求域名必须绑定阿里云的服务器 (且要求服务器套餐费用不得低于 100 元/年);
很明显, 我是不可能在这种事情上花一分钱的, 于是只能另寻他路;
域名解析的迁移
首先登录 万网域名管理, 修改 DNS 服务器, 用 cloudflare 代替万网来托管域名解析:
同时在 cloudflare 控制台 配置 CNAME 规则:
定义 Worker 反向代理
编写反向代理逻辑 url-implict-redirect.js:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34/**
* Welcome to Cloudflare Workers! This is your first worker.
*
* - Run "npm run dev" in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run "npm run deploy" to publish your worker
*
* Learn more at https://developers.cloudflare.com/workers/
*/
export default {
async fetch(request) {
const url = new URL(request.url);
const path = url.pathname;
// 目标域名(实际目标)
const targetDomain = "https://zshellzhang.atomgit.net";
// 处理路径:
// - / → 代理到 /zshell
// - /about → 代理到 /zshell/about
// - /zshell → 代理到 /zshell
// - /zshell/about → 代理到 /zshell/about
const targetPath = path.startsWith("/zshell") ? path : `/zshell${path}`;
const response = await fetch(`${targetDomain}${targetPath}`, {
headers: request.headers
});
// 返回响应(保持原始URL)
return new Response(response.body, {
status: response.status,
headers: response.headers
});
}
};
部署并监控 Worker 的状态: url-implict-redirect;
将域名绑定 Worker

效果如下: