快速移动配置到CloudFlare Workers

时间:2018-04-17 15:51:55

标签: cloudflare cloudflare-workers

如何重写以下代码以使用CF Workers功能?

# Start 
if(req.url ~ "^/app" ) { 
set req.url = regsub(req.url, "^/app/", "/"); 
set req.http.X-DR-SUBDIR = "app"; 
} 
#end condition

1 个答案:

答案 0 :(得分:1)

Cloudflare Workers实现了Service Worker标准,因此您需要重新实现您根据服务工作者发布的VCL代码段。

在我向您展示如何执行此操作之前,请考虑当https://example.com/apple的请求到达代理时会发生什么。我希望^/app的第一个正则表达式匹配,但^/app/的第二个正则表达不匹配 - 即,请求将在不更改URL的情况下传递,但添加了一个X-DR-SUBDIR: app标题。

我怀疑行为是一个错误,所以我首先要实现一个工作者,好像第一个正则表达式是^/app/

addEventListener("fetch", event => {
  let request = event.request

  // Unlike VCL's req.url, request.url is an absolute URL string,
  // so we need to parse it to find the start of the path. We'll
  // need it as a separate object in order to mutate it, as well.
  let url = new URL(request.url)

  if (url.pathname.startsWith("/app/")) {
    // Rewrite the URL and set the X-DR-SUBDIR header.

    url.pathname = url.pathname.slice("/app".length)

    // Copying the request with `new Request()` serves two purposes:
    //   1. It is the only way to actually change the request's URL.
    //   2. It makes `request.headers` mutable. (The headers property
    //      on the original `event.request` is always immutable, meaning
    //      our call to `request.headers.set()` below would throw.)
    request = new Request(url, request)

    request.headers.set("X-DR-SUBDIR", "app")
  }

  event.respondWith(fetch(request))
})

要重新审视https://example.com/apple案例,如果我们真的想要一个讽刺地再现VCL片段行为的Cloudflare Worker,我们可以更改这些行(评论已删除):

  if (url.pathname.startsWith("/app/")) {
    url.pathname = url.pathname.slice("/app".length)
    // ...
  }

到这些:

  if (url.pathname.startsWith("/app")) {
    if (url.pathname.startsWith("/app/")) {
      url.pathname = url.pathname.slice("/app".length)
    }
    // ...
  }