711 字
4 分钟
手把手教你cloudflare优选

对比#

  1. 无优选
  2. 优选

可见,优选过的网站响应速度有很大提升,cdn节点也多了,可以大大提高网站的访问速度


你需要的东西#

  1. 两个域名

  2. 一张银行卡(不建议使用虚拟),需要绑定到cloudflare账户,在免费使用额度内不会扣费

开搞!#

  1. 两个域名

(以下称作源域名和目标域名,目标域名就是访问的域名),比如: rz7.top 和 rz101.com

要求源域名托管到cloudflare,目标域名非使用cloudflare的dns服务

这里我们让rz101.com成为目标域名,rz7.top成为源域名

  1. 源域名添加一个记录,指向你的源站打开cf代理

  2. 前往源域名的SSL/TLS -> 自定义主机名。设置回退源为刚刚添加的记录域名。

  3. 点击添加自定义主机名。设置一个自定义主机名,比如:rz101.com, 源服务器为默认(也可以设置为其他域名)

按照指示进行域名验证

  1. 最后在你的目标域名的DNS中添加一条记录,CNAME到优选域名

关于优选域名:

  1. fenliu.072103.xyz
  2. cf.090227.xyz
  3. cloudflare.182682.xyz
  1. 优选完成,尝试访问。

(新)使用workers路由反代再进行优选 (新版教程#

本方法的原理为通过Worker反代你的源站,然后将Worker的入口节点进行优选。此方法不是传统的优选,源站接收到的Hosts头仍然是直接指向源站的解析

以下代码是原Github全站反代代码的二改以实现Worker路由接入优选,可能有多余逻辑或者不完全适配于优选需求

创建一个Cloudflare Worker,写入代码

// 域名前缀映射配置
const domain_mappings = {
'源站.com': '最终访问头.',
//例如:
//'rz7.top': 'rz101',
//则你设置Worker路由为rz101.*都将会反代到rz7.top
};
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const current_host = url.host;
// 强制使用 HTTPS
if (url.protocol === 'http:') {
url.protocol = 'https:';
return Response.redirect(url.href, 301);
}
const host_prefix = getProxyPrefix(current_host);
if (!host_prefix) {
return new Response('Proxy prefix not matched', { status: 404 });
}
// 查找对应目标域名
let target_host = null;
for (const [origin_domain, prefix] of Object.entries(domain_mappings)) {
if (host_prefix === prefix) {
target_host = origin_domain;
break;
}
}
if (!target_host) {
return new Response('No matching target host for prefix', { status: 404 });
}
// 构造目标 URL
const new_url = new URL(request.url);
new_url.protocol = 'https:';
new_url.host = target_host;
// 创建新请求
const new_headers = new Headers(request.headers);
new_headers.set('Host', target_host);
new_headers.set('Referer', new_url.href);
try {
const response = await fetch(new_url.href, {
method: request.method,
headers: new_headers,
body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined,
redirect: 'manual'
});
// 复制响应头并添加CORS
const response_headers = new Headers(response.headers);
response_headers.set('access-control-allow-origin', '*');
response_headers.set('access-control-allow-credentials', 'true');
response_headers.set('cache-control', 'public, max-age=600');
response_headers.delete('content-security-policy');
response_headers.delete('content-security-policy-report-only');
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response_headers
});
} catch (err) {
return new Response(`Proxy Error: ${err.message}`, { status: 502 });
}
}
function getProxyPrefix(hostname) {
for (const prefix of Object.values(domain_mappings)) {
if (hostname.startsWith(prefix)) {
return prefix;
}
}
return null;
}

在workers中创建路由

手把手教你cloudflare优选
https://w.r-z.top/posts/cloudflare-saas/
作者
W.R.Z
发布于
2025-11-15
许可协议
CC BY-NC-SA 4.0