边缘安全加速平台 EO 批量重定向

该示例捕获传入的 HTTP 请求,并通过预定义的重定向映射表,实现了指定路径自动跳转至对应 URL,可用于网站迁移或错误页面的自定义处理。

相关产品
边缘安全加速平台 EO 产品页,含版本规格、价格与购买入口。

一、示例代码

// 添加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

赞 (0)
上一篇 4天前
下一篇 4天前