一、示例代码
async function handleEvent(event) { const { request } = event; const urlInfo = new URL(request.url); // 正则表达式匹配/test/后面跟着1或2个非斜杠的路径段 const regexp = /^\\/test\\/([^\\/]+)(?:\\/([^\\/]+))?\\/?$/; // 检查路径是否匹配正则表达式 if (regexp.test(urlInfo.pathname)) { const matches = urlInfo.pathname.match(regexp); let newPathname = '/test/'; // 构造新的路径名,根据匹配的路径段数量,可能是一个或两个 newPathname += matches[1]; // 第一个路径段 if (matches[2]) { newPathname += '/' + matches[2]; // 第二个路径段,如果有的话 } // 确保以index.html结尾 newPathname += '/index.html'; // 更新URLInfo的pathname urlInfo.pathname = newPathname; } // 使用更新后的URLInfo发起请求 const response = await fetch(urlInfo.toString(), { method: request.method, headers: request.headers, redirect: 'manual', body: request.body, }); // 将响应返回给事件 return event.respondWith(response);}// 为每个fetch事件调用handleEvent函数addEventListener('fetch', (event) => { handleEvent(event);});
二、示例预览
1. 在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,在路径中携带 /test/segment1 实现动态改写访问 https://www.example.com/test/segment1/index.html
2. 在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,在路径中携带 /test/segment1/segment2 实现动态改写访问 https://www.example.com/test/segment1/segment2/index.html
3. 在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,在路径中携带非正则匹配内容,如:/test/test1
三、相关参考
·Runtime APIs: Request
·Runtime APIs: Response