如何使用 cloudflare workers薅张小龙的小而美

20 min read
addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  // Check if the request path matches the pattern: /mmbiz_(jpg|png|gif|jpeg|webp|bmp)/(.*)
  if (/^\/mmbiz_(jpg|png|gif|jpeg|webp|bmp)\/(.*)/.test(url.pathname)) {
    // Replace the path prefix to proxy the request to https://mmbiz.qpic.cn
    url.host = "mmbiz.qpic.cn";
    url.pathname = url.pathname.replace(/^\/mmbiz_(jpg|png|gif|jpeg|webp|bmp)\//, "/mmbiz_$1/");

    // Create a new request object with the updated URL and headers
    const newRequest = new Request(url.toString(), {
      method: request.method,
      headers: request.headers,
    });

    // Set the Host header and remove the Referer header
    newRequest.headers.set("Host", "mmbiz.qpic.cn");
    newRequest.headers.delete("Referer");

    // Send the request and return the response
    return fetch(newRequest);
  }

  // Return the original request if the path doesn't match the pattern
  return fetch(request);
}