【问题标题】:Move Fastly config to CloudFlare Workers将 Fastly 配置迁移到 CloudFlare Workers
【发布时间】:2018-09-27 16:20:24
【问题描述】:

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

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

【问题讨论】:

    标签: cloudflare cloudflare-workers


    【解决方案1】:

    Cloudflare Workers 实现了 Service Worker 标准,因此您需要根据 Service Worker 重新实现您发布的 VCL 代码 sn-p。

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

    我怀疑这种行为是一个错误,所以我将首先实现一个 worker,就好像第一个正则表达式是 ^/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 sn-p 行为的 Cloudflare Worker,我们可以更改这些行(省略 cmets):

      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)
        }
        // ...
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 2020-08-12
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多