利用CloudFlare的Workers和Pages反代Github并缓存实现Github文件加速访问
网上有很多Github加速访问的方法,如果你也想拥有一个属于自己独享的Github加速,可以按照此教程搭建一个你自己的反代来实现加速Github文件访问的服务。
CloudFlare
CloudFlare提供的不仅仅是CDN,而是一个快速、敏捷、安全的全球网络。
CloudFlare通过全球边缘网络实现超快速的静态和动态内容交付。对内容的高速缓存方式实行精确控制,降低带宽成本,并充分利用内置的不计量 DDoS 保护。
今天我们使用 CloudFlare Workers 和 CloudFlare Pages来搭建我们的反代服务。
通过CloudFlare Workers实现反代
没有CloudFlare账号可以去简单注册一个,以后肯定必然会用的到!
首先,创建一个CloudFlare Workers服务,步奏如下图。


创建好以后,编辑CloudFlare Workers服务,并写入以下代码即可。
addEventListener("fetch", (event) => {
let url = new URL(event.request.url);
url.hostname = "cdn.jsdelivr.net"; //你需要反代的域名
let request = new Request(url, event.request);
event.respondWith(fetch(request));
});


由于CloudFlare Workers自带的免费works.dev域名国内已经无法访问了,需要通过绑定自定义域名.



绑定好域名,我们就可以直接访问了!
通过CloudFlare Pages实现反代
2.将脚本文件托管在Github上,可实时更新.
1.直接上传反代脚本.
首先创建CloudFlare Pages服务,选择直接上传.


然后创建一个项目文件夹(名字可以随意),在文件夹内创建一个_worker.js的文件,并写入以下代码:
export default {
async fetch(request, env) {
const _url = new URL(request.url);
_url.hostname = _url.pathname.startsWith("/gh/") ? "cdn.jsdelivr.net" : "www.baidu.com";
const req = new Request(_url, request);
return fetch(req);
},
};
将项目文件夹拖拽到上传区域进行上传(注意:是上传项目文件夹),然后部署项目.


2.将脚本文件托管在Github上,可实时更新.
首先创建一个Git项目,然后creating a new file 一个_worker.js的JS文件并写入以下代码保存.
export default {
async fetch(request, env) {
const _url = new URL(request.url);
_url.hostname = _url.pathname.startsWith("/gh/") ? "cdn.jsdelivr.net" : "www.baidu.com";
const req = new Request(_url, request);
return fetch(req);
},
};




然后创建CloudFlare Pages服务,选择连接到Git,选择你刚刚创建的Git项目,开始设置。
使用默认配置,并保存部署即可。



到此,我们通过CloudFlare Pages创建的服务已经成功了.
由于CloudFlare Pages自带的免费pages.dev域名国内访问也是很不稳定,这里极其建议同学们绑定自定义域名进行访问!
方法也很简单,首先打开CloudFlare Pages,选择你刚刚创建的服务
然后 点击自定义域 => 设置自定义域名 => 进行CNAME解析 => 激活域 即可大功告成!



以上内容,我们已经完成了两种反向代理的搭建,大家自行选择一种,坚持能跑就行的原则,继续接下来的缓存步骤.
配置Github加速文件的边缘缓存
选择你得域名,点击 规则 => 页面规则 => 创建页面规则
如图所示,设置以下规则,并保存部署页面规则即可.



最后我们访问一下,感受一下速度~