本代

游戏开发 / 服务器 / 踩坑记录

用 Cloudflare Worker 给静态资源站做中转加速

· 阅读约 5 分钟

做 Godot Web 版时会从一些免费素材站拉模型和贴图,国内直连经常很慢甚至超时。套一层 Cloudflare Worker 中转,成本为零,几十行脚本搞定。

核心思路:URL 即代理路径

把目标地址直接拼在 Worker 的路径后面:

https://your-worker.your-subdomain.workers.dev/https://example.com/models/boy.glb

Worker 从 pathname 里还原出真实 URL,转发请求,再把响应原样吐回来。

一定要加白名单

开放代理等于把 Cloudflare 的额度送给别人刷,很容易被封号。只允许自己用到的域名:

const ALLOWED_HOSTS = ["quaternius.com", "www.quaternius.com"];

if (!ALLOWED_HOSTS.includes(target.hostname)) {
  return new Response("域名不在白名单内", { status: 403 });
}

清理 Cloudflare 注入的请求头

源站看到 cf-connecting-ip 这类头会识别出代理流量并拒绝,转发前删掉:

const headers = new Headers(request.headers);
for (const h of ["host", "cf-connecting-ip", "cf-ipcountry", "cf-ray", "cf-visitor"]) {
  headers.delete(h);
}
headers.set("accept-encoding", "gzip, br");

改写 302 跳转

素材站常见 http → https 或补 www 的跳转。如果直接透传,浏览器下一跳就绕开了代理:

const location = respHeaders.get("location");
if (location) {
  const abs = new URL(location, target).toString();
  respHeaders.set("location", incoming.origin + "/" + abs);
}

配合 redirect: "manual",把跳转地址重新拼回代理路径。

相对路径资源:注入

HTML 里的 /css/x.css 这种根相对路径,浏览器会解析到 Worker 域名根下,而不是源站。解决办法是改写绝对链接,再注入 <base>:

for (const host of ALLOWED_HOSTS) {
  html = html.split("https://" + host).join(prefix + "https://" + host);
}
html = html.replace(
  /<head([^>]*)>/i,
  '<head$1><base href="' + prefix + target.origin + target.pathname + '">'
);

删掉会挡住渲染的响应头

图片、CSS、JS 这类资源不用改内容,直接流式透传 upstream.body 就行,别整个读进内存。


← 返回首页