基于正则的 URL 改写
该示例捕获传入的 HTTP 请求,根据 URL 路径使用正则表达式进行匹配,并在匹配到特定内容时实现 URL 改写访问 index.html 页面。适用于将对指定目录下的任意请求统一重写为访问主页(通常是index.html),以便通过前端路由来处理不同的页面请求。
示例代码
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的pathnameurlInfo.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


相关参考