一、示例代码
// 添加fetch事件监听器,当有请求进入时触发,使用handleRequest函数处理请求,并返回响应async function handleRequest(request) { // 定义目标外部主机名 const yourExternalHostname = "www.example.com"; // 创建路径到重定向URL的映射 const redirectMap = new Map([ ["/foo", "https://" + yourExternalHostname + "/redirect1"], ["/bar", "https://" + yourExternalHostname + "/redirect2"], ["/baz", "https://" + yourExternalHostname + "/redirect3"], ]); // 解析请求的URL const url = new URL(request.url); // 获取URL的路径部分 const path = url.pathname; // 检查路径是否在重定向映射中,如果是则进行重定向 if (redirectMap.has(path)) { return Response.redirect(redirectMap.get(path), 301); } else { // 如果路径不在映射中,返回404状态 return new Response('Not Found', { status: 404 }); }}// 当有请求事件发生时,使用handleRequest函数处理addEventListener('fetch', event => { event.respondWith(handleRequest(event.request));});
二、示例预览
在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,在路径中携带/bar将实现到自动 301 重定向至 https://www.example.com/redirect2
预览如下,当前显示 404 因目标主机名 www.example.com 路径 /redirect2 下无资源,你需按实际替换目标主机名和路径。
三、相关参考
·Runtime APIs: Request
·Runtime APIs: Response