Cloudflare worker 反向代理

发布于 / 资源分享 / 0 条评论

项目代码:



#使用前请将代码中的两个example.com替换成你自己的域名

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const { pathname, searchParams } = new URL(request.url)

  if (pathname === '/') {
    // 返回带有输入框的 HTML 页面
    return new Response('<input type="text" id="urlInput"><button onclick="redirect()">Go</button><script>function redirect() { const url = document.getElementById("urlInput").value; window.location.href = "https://example.com/" + encodeURIComponent(url); }</script>', {
      headers: { 'Content-Type': 'text/html' }
    })
  } else {
    // 获取要访问的网页链接
    const url = decodeURIComponent(pathname.slice(1))

    // 反向代理访问网页
    const response = await fetch(url, request)

    // 如果响应是301或302重定向
    if (response.status === 301 || response.status === 302) {
      const redirectUrl = response.headers.get('Location')

      // 生成重定向的 URL
      const newUrl = `https://example.com/${encodeURIComponent(redirectUrl)}`

      // 创建一个新的请求
      const newRequest = new Request(newUrl, request)
      return handleRequest(newRequest)
    }

    // 将响应返回给用户
    return new Response(response.body, response)
  }
}

有什么用?

最大的作用其实就是加速各种静态文件,比如你托管在github上的项目别人下载不动,就直接用这个worker生产链接给他用,还比如说一些大文件镜像速度满,就直接用这个加速

举个例子:

加速ubuntu iso镜像

本文基于《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
转载原创文章请注明,转载自: 沧水的博客 » Cloudflare worker 反向代理
Not Comment Found