GitHub 站点经常有 TimeoutReset 的情况发生,有时候又懒得开梯子,所以想零成本的做一个 GitHub 的线上代理。

刚好 CloudFlare 有免费 Worker 功能,同时 Cloudflare 会对静态页面做 CDN 缓存,也会加快我们访问 GitHub 的速度。

有大神写好了代码,实现对 GitHub 做全球代理,将大神们的成果抄录,以备不时之需。

实施步骤

步骤很简单,没必要写教程,大概就是:

  1. 注册 cloudflare 账号
  2. 创建 workerpages 应用
  3. 粘贴代码保存并发布
  4. 绑定自定义域名

实现代码

worker 代理 GitHub 网站

以下代码,能实现用自己的域名打开 GitHub 站使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export default {
async fetch(request, env) {
const _url = new URL(request.url);
const hostname = _url.hostname
_url.hostname = "github.com"
const req = new Request(_url, request);
req.headers.set('origin', 'https://github.com');

const res = await fetch(req);
let newres = new Response(res.body, res);

let location = newres.headers.get('location');
if (location !== null && location !== "") {
location = location.replace('://github.com', '://'+hostname);
newres.headers.set('location', location);
}
return newres
},
};

其中 GitHub 对于 Post 请求,会检查 Origin 头,如果不是 GitHub 自身的域名,会直接返回 422 错误。

这里使用以下代码,将转发给 GitHub 的 header 覆盖 Origin

1
req.headers.set('origin', 'https://github.com');

当用户没有登录的时候,响应的 Location 字段会被设置为 https://github.com/login,这里为了避免浏览器跳转到 GitHub 官网,修改了 location 字段到请求域。

1
2
3
4
5
let location = newres.headers.get('location');
if (location !== null && location !== "") {
location = location.replace('://github.com', '://'+hostname);
newres.headers.set('location', location);
}

worker 反代指定网站

1
2
3
4
5
6
7
8
9
10
11
addEventListener(
"fetch",event => {
let url=new URL(event.request.url);
url.hostname="abc.def.xyz"; // 修改成自己的节点IP/域名
url.protocol='https'; // 如为http协议请修改为http
let request=new Request(url,event.request);
event. respondWith(
fetch(request)
)
}
)

pages 反代指定网站

1
2
3
4
5
6
7
8
9
10
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);
},
};

参考链接

  1. 利用CloudFlare的Workers和Pages反代Github并缓存实现Github文件加速访问
  2. 利用CloudFlare的Worker反代Github站点
  3. 使用 CloudFlare Workers 反代节点