批量重定向

最近更新时间:2024-06-14 17:33:21

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

示例代码

// 添加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 下无资源,您需按实际替换目标主机名和路径。




相关参考