是否可以使用 Cloudflare Service Worker 作为代理服务器?



这只是一个初学者级别的问题,寻求一些建议,由于缺乏知识,以下内容也可能误用一些关键术语,但希望可以向所有人传达关键信息:

背景:
我的公司在AWS中托管一个网站,除了无法在中国加载之外一切正常,因为众所周知的中国防火墙将阻止中国境外所有未注册/未经许可的网站; 最好的解决方案可能是在中国托管服务器并获得中国政府批准的ICP许可证, 但这需要时间和许多其他考虑。因此,我们现在正在寻找一些替代方案,让来自中国的客户能够从我们的网站阅读内容。

主要思想:
使用 Cloudflare 服务工作者首先从给定网页获取 HTTP 资源,然后由 Service Worker 将 HTTP 内容发送给用户(因为 Cloudflare 在中国可以访问(

示例:
让 Cloudflare 的注册服务工作者 URL 为: sample.workers.dev 要服务的目标网站内容:google.com
当用户尝试访问此域 (sample.workers.dev
( 时,服务工作者应尝试从后端 google.com 加载所有 HTTP 内容,包括图像、脚本和 css,然后将 HTTP 内容直接返回给用户

这将适用于我公司的客户,因为我们通常会生成一个 url 并通过电子邮件或其他方式发送给用户,因此我们可以向他们发送在中国可以访问的第三方 URL,同时实际从我们的原始网站加载内容。

我已经尝试了Cloudflare给出的所有示例:https://developers.cloudflare.com/workers/templates/但到目前为止,还没有运气来存档我想要的确切内容。

有什么想法吗?

是的,这是可能的。 我记得Cloudflare的某人以它为例实现了它。

找到了:https://github.com/lebinh/cloudflare-workers/blob/master/src/proxy.ts

但是,Cloudflare 工作人员现在确实支持流式 API IIRC,因此有更好的方法可以做到这一点。

/**
* HTTP Proxy to arbitrary URL with Cloudflare Worker.
*/
/**
* Cloudflare Worker entrypoint
*/
if (typeof addEventListener === 'function') {
addEventListener('fetch', (e: Event): void => {
// work around as strict typescript check doesn't allow e to be of type FetchEvent
const fe = e as FetchEvent
fe.respondWith(proxyRequest(fe.request))
});
}
async function proxyRequest(r: Request): Promise<Response> {
const url = new URL(r.url)
const prefix = '/worker/proxy/'
if (url.pathname.startsWith(prefix)) {
const remainingUrl = url.pathname.replace(new RegExp('^' + prefix), '')
let targetUrl = decodeURIComponent(remainingUrl)
if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
targetUrl = url.protocol + '//' + targetUrl
}
return fetch(targetUrl)
} else {
return new Response('Bad Request', {status: 400, statusText: 'Bad Request'})
}
}
interface FetchEvent extends Event {
request: Request;
respondWith(r: Promise<Response> | Response): Promise<Response>;
}

最新更新