背景
在上一篇文章中,我在 Hax VPS 上通过 Caddy 成功反代了 GitHub 的主域名。但是,因为我仅仅只是通过 Caddy 原样返回 GitHub 网页的响应头以及内容,而没有替换静态资源的 URL,因此使用浏览器打开反代地址时,可能会出现网页加载不出来或者用户头像加载失败的情况。所以,有必要反代 GitHub 的静态资源,并对主站返回的内容进行替换。
下载含有内容替换模块的 Caddy 并替换原有文件
使用 APT 安装的 Caddy 不包括能够替换返回内容的任何模块,因此,我们需要获得一个自带响应内容替换模块的 Caddy 。这里我选择的模块是官方的 replace-response
,我们可以在 Caddy 官网下载页面直接下载现成的编译好的 Caddy 。对于 Hax ,只需要在 “Platform” 处选择“Linux amd64”,然后在“Filter packages and modules”输入框中输入 replace-response
,并点击“Download”即可开始下载。
下载完成后,将下载下来的可执行文件上传到 VPS 并覆盖原有 Caddy 的可执行文件(位于 /usr/bin/caddy
)。也可以在 VPS 上通过命令行完成下载和替换,只需要执行 curl -o /usr/bin/caddy [下载地址]
即可。
替换完成后,需要停止 Caddy 服务,执行 systemctl stop caddy
即可。
编写配置文件
知识储备
1、Github 静态资源域名:
用户头像:avatars.githubusercontent.com
仓库中的文件:raw.githubusercontent.com
release 文件codeload.github.com
和 objects.githubusercontent.com
2、使用 replace-response
替换内容的语法
replace {
"原文本1" "新文本1"
"原文本2" "新文本2"
"原文本3" "新文本3"
...
}
3、替换重定向域名(Location)
header >Location "https://旧域名/(.*)" "https://新域名/$1"
编写配置文件
将上节展示的 Caddyfile 内容修改为:
github.example.com {
tls xxx@example.com
replace {
"//github.com/" "//github.example.com/"
"\"github.com\"" "\"github.example.com\""
"avatars.githubusercontent.com" "avatars.github.example.com"
"github.githubassets.com" "assets.github.example.com"
}
header -Content-Security-Policy
header >Location "https://codeload.github.com/(.*)" "https://codeload.github.example.com/$1"
header >Location "https://objects.githubusercontent.com/(.*)" "https://objects.github.example.com/$1"
header >Location "https://raw.githubusercontent.com/(.*)" "https://raw.github.example.com/$1"
reverse_proxy https://github.com {
header_up Accept-Encoding identity
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
}
}
avatars.github.example.com {
tls xxx@example.com
header -Timing-Allow-Origin
reverse_proxy https://avatars.githubusercontent.com {
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
}
}
codeload.github.example.com {
tls xxx@example.com
header -Timing-Allow-Origin
reverse_proxy https://codeload.github.com {
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
}
}
assets.github.example.com {
tls xxx@example.com
header -Timing-Allow-Origin
reverse_proxy https://github.githubassets.com {
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
}
}
objects.github.example.com {
tls xxx@example.com
header -Timing-Allow-Origin
reverse_proxy https://objects.githubusercontent.com {
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
}
}
raw.github.example.com {
tls xxx@example.com
header -Timing-Allow-Origin
reverse_proxy https://raw.githubusercontent.com {
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
}
}
注意将域名和邮箱换成自己的。
PS:由于 CloudFlare 免费套餐的 SSL 证书不支持三级域名(注:此处指类似于 level3.level2.example.com
的域名),而我用的正是 CloudFlare 的 免费套餐 CDN ,因此我将这里的三级域名改成了二级的(格式为 github-xxx.example.com
),以保证不会出现访问错误。
重启 Caddy 进程
一句 systemctl reload caddy
完事。