如何重写以下代码以使用 CF Workers 功能?
# Start
if(req.url ~ "^/app" ) {
set req.url = regsub(req.url, "^/app/", "/");
set req.http.X-DR-SUBDIR = "app";
}
#end condition
如何重写以下代码以使用 CF Workers 功能?
# Start
if(req.url ~ "^/app" ) {
set req.url = regsub(req.url, "^/app/", "/");
set req.http.X-DR-SUBDIR = "app";
}
#end condition
Cloudflare Workers 实现了 Service Worker 标准,因此您需要重新实现您根据 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
案例,如果我们真的想要一个 Cloudflare Worker,它迂腐地再现 VCL 片段的行为,我们可以更改这些行(注释省略):
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)
}
// ...
}