在上一篇文章 使用Cloudflare Saas加速网站访问 中, 我们顺利使用了Cloudflare For SaaS来加速我们的网站, 这篇网站教大家如何使用华为云来进行国内外分流解析

下文的CF即Cloudflare

分流解析的原因

尽管我们使用了CF SaaS加速网站, 但是因为CF糟糕的国内线路, 导致国内用户无法流畅访问

并且由于CF优秀的国际线路导致我们无法舍弃掉它, 所以我们就可以通过CF SaaS+分流解析来使国内用户走国内优化CDN, 国外用户走CF CDN

准备阶段

本文是在前文的基础上写的, 请先阅读前文来保证您能够正常配置

一个Cloudflare账户(需开启SaaS服务), 一个华为云DNS账户, 一个托管在Cloudflare的域名, 一个国内优化CDN(本文以DokiCDN为例)

托管子域名到华为云

打开我们的Cloudflare DNS管理页面, 为子域名添加NS记录, 并等待解析完成

1
2
3
4
ns1.huaweicloud-dns.com.
ns1.huaweicloud-dns.cn.
ns1.huaweicloud-dns.net.
ns1.huaweicloud-dns.org.

1

与此同时, 打开华为云DNS, 创建公网域名xxx.333375.xyz

这样就算是托管完毕

配置CDN

打开我们的CDN后台, 我们以DokiCDN的GoEdge系统为例

首先添加网站, 源站是你回源域名解析的值, 完成之后会给出一个你需要CNAME解析的域名

2

然后来到华为云添加记录, 设置分流解析, 中国大陆解析到国内优化CDN, 境外解析到回源域名

3

4

配置自动化SSL

配置CF的自动SSL

前文中配置了DCV委派, 我们由于将NS修改到了华为云, 所以我们需要重新添加CNAME记录

配置GoEdge的自动SSL

本小段教程仅针对GoEdge等仅支持http验证的系统, 如果你的CDN系统支持DNS账户验证, 建议直接使用DNS账户验证

由于GoEdge系统仅支持http验证申请证书, 并且我们仅在境内解析了DokiCDN, 而Let’s Encrypt验证http的服务器在国外, 所以在以上条件结合下我们需要特殊的配置来申请证书

我的解决方案是通过CF Workers路由来验证

首先打开Cloudflare的Workers, 点击创建Workers

5

6

7

然后编辑代码, 记得将 cdn.yourcdn.comxxx.333375.xyz 修改为你自己的, 点击保存部署(如果是手机操作, 一定要在粘贴之后将最后一行的两个符号删除)

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
35
36
37
38
39
40
41
42
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
const url = new URL(request.url)

if (url.pathname.startsWith('/.well-known/acme-challenge/')) {
const targetUrl = `http://cdn.yourcdn.com${url.pathname}${url.search}` //修改为你的CDN分配的域名

const modifiedHeaders = new Headers(request.headers)
modifiedHeaders.set('Host', 'xxx.333375.xyz') //修改为你的网站的域名

const modifiedRequest = new Request(targetUrl, {
method: request.method,
headers: modifiedHeaders,
body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : null
})

try {
const response = await fetch(modifiedRequest)

const modifiedResponse = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers
})

return modifiedResponse
} catch (error) {
return new Response('Proxy Error: ' + error.message, {
status: 502,
statusText: 'Bad Gateway'
})
}
}

return new Response('Not Found', {
status: 404,
statusText: 'Not Found'
})
}

保存并退出后点击 设置->添加域和路由->路由, 添加路由 xxx.333375.xyz/.well-known/acme-challenge/* 并将 xxx.333375.xyz 修改为你自己的, 然后点击添加路由

8

9

之后回到CDN管理页面, 申请证书并配置

10

总结

用户访问流程:

flowchart LR
    用户浏览器-->yourdomain.com
    yourdomain.com--国外用户-->CF-CDN--回源-->origin.yourdomain.com-->服务器
    yourdomain.com--国内用户-->优化CDN-->服务器
    服务器--返回内容-->用户浏览器
    SSL验证服务器-->yourdomain.com/.well-known/acme-challenge/1234-->Workers路由--Host:yourdomain.com-->cdn.yourcdn.com/.well-known/acme-challenge/1234
    cdn.yourcdn.com/.well-known/acme-challenge/1234-->SSL验证服务器

示例: https://xxx.333375.xyz/