冰豆网

分享网络精彩
bingdou.com.cn

EdgeOne 301重定向、批量重定向、基于请求区域重定向边缘函数

时间:2025-07-25加入收藏

301重定向
这个示例展示了如何使用HTTP 301状态码自动且永久地重定向客户端请求到一个预设的网站地址。它通常用于永久性的网站迁移或合并。
示例代码:

// Target redirect address
const destinationLocation = 'https://www.example.com';

// HTTP status code, used for permanent redirects
const statusCode = 301;

// Async function used to handle requests
async function handleRequest(request) {
    // Return a redirect response with the specified target location and status code.
    return Response.redirect(destinationLocation, statusCode);
}

// Add a fetch event listener to intercept requests and respond using the handleRequest function.
addEventListener("fetch", event => {
    event.respondWith(handleRequest(event.request));
});


批量重定向
该示例捕获传入的 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 下无资源,您需按实际替换目标主机名和路径。

基于请求区域重定向
该示例通过判断客户端所属区域,自动重定向到所属区域的目标网址。实现了通过边缘函数根据客户端所属区域分发请求。
示例代码:

// 所有区域网址集
const urls = {
  CN: 'https://www.example.com/zh-CN',
  US: 'https://www.example.com/en-US',
};

// 默认重定向网址
const defaultUrl = 'https://www.example.com/en-US';

/**
 * 根据当前请求所在的区域,重定向到目标网址
 * @param { Request } request
 */
function handleRequest(request) {
  // 获取当前请求所在区域
  const alpha2code = request.eo.geo.countryCodeAlpha2;
  // 重定向目标网址
  const url = urls[alpha2code] || defaultUrl;

  return Response.redirect(url, 302);
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

打 赏
打赏二维码

TGA: 技巧

分享到:


官方微信二维码冰豆网官方微信公众号