You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Fastly配置迁移至Cloudflare Workers:如何改写代码适配该功能?

Convert Fastly VCL Logic to Cloudflare Workers

Got it, let's translate that Fastly VCL snippet into functional Cloudflare Workers code. Your original logic checks if the request URL starts with /app, rewrites the URL to strip the /app/ prefix, and sets a custom header. Here's how to replicate that in Workers:

Full Workers Code

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

async function handleRequest(request) {
  const url = new URL(request.url)
  
  // Match the original Fastly condition: check if URL starts with "/app"
  if (url.pathname.match(/^\/app/)) {
    // Rewrite the URL: replace "/app/" with "/" (matches regsub behavior)
    url.pathname = url.pathname.replace(/^\/app\//, '/')
    
    // Create a new request with the rewritten URL and add the custom header
    const modifiedRequest = new Request(url.toString(), {
      headers: new Headers(request.headers),
      method: request.method,
      body: request.body,
      redirect: request.redirect
    })
    modifiedRequest.headers.set('X-DR-SUBDIR', 'app')
    
    // Forward the modified request to the origin
    return fetch(modifiedRequest)
  }
  
  // If the URL doesn't match, pass the original request through
  return fetch(request)
}

How This Maps to Your Fastly Config

Let's break down each part to match your original VCL:

  • Condition check: if (url.pathname.match(/^\/app/)) does the same as if(req.url ~ "^/app") — it checks if the request path starts with /app.
  • URL rewrite: url.pathname.replace(/^\/app\//, '/') replicates regsub(req.url, "^/app/", "/"), stripping the /app/ prefix from the path.
  • Custom header: modifiedRequest.headers.set('X-DR-SUBDIR', 'app') is the equivalent of set req.http.X-DR-SUBDIR = "app";, adding the header to the request sent to your origin.

A couple of quick notes:

  • We use new URL() to safely parse and modify the request URL (Cloudflare Workers recommends this over raw string manipulation for reliability).
  • We create a new Request object instead of modifying the original directly, since request objects are immutable in Workers.

内容的提问来源于stack exchange,提问作者stevehart808

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:21:22