Cloudflare Worker利用反向代理来加速web站点

Posted by cmbjx on November 13, 2024

提升Cloudflare速度!如何优化国内访问体验?实测优选方案大揭秘!最终版本

Worker.js代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});
 
async function handleRequest(request) {
  const url = new URL(request.url);
 
  // 指定目标反向代理的 URL
  const targetUrl = `https://example.com${url.pathname}`;
 
  // 创建一个新的请求
  const modifiedRequest = new Request(targetUrl, {
    method: request.method,
    headers: request.headers,
    body: request.body,
    redirect: 'follow'
  });
 
  // 获取目标服务器的响应
  let response = await fetch(modifiedRequest);
 
  // 检查响应类型并重写内容
  const contentType = response.headers.get('content-type') || '';
  if (contentType.includes('text/html') || contentType.includes('text/css') || contentType.includes('application/javascript')) {
    // 将响应内容转为文本
    let text = await response.text();
 
    // 替换内容:例如,将 example.com 替换为 yoursite.com
    text = text.replace(/example\.com/g, 'yoursite.com');
 
    // 返回修改后的响应
    return new Response(text, {
      status: response.status,
      headers: response.headers
    });
  }
 
  // 如果不是需要重写的类型,则直接返回原始响应
  return response;
}