将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 asif(req.url ~ "^/app")— it checks if the request path starts with/app. - URL rewrite:
url.pathname.replace(/^\/app\//, '/')replicatesregsub(req.url, "^/app/", "/"), stripping the/app/prefix from the path. - Custom header:
modifiedRequest.headers.set('X-DR-SUBDIR', 'app')is the equivalent ofset 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
Requestobject instead of modifying the original directly, since request objects are immutable in Workers.
内容的提问来源于stack exchange,提问作者stevehart808
相关产品推荐
相关产品推荐

