EdgeOne使用中间件实现301重定向

AI大语言模型

EdgeOne支持在配置文件中实现URL重定向、URL重写。但edgeone.json规则单一,且最多只支持100条重定向。使用中间件可以定义更灵活、数量更多的重定向规则。

在项目根目录创建中间件middleware.js:

import redirects from "./redirects.js";

export function middleware(context) {
    const { request, redirect } = context;
    const url = new URL(request.url);
    const baseUrl = `${url.protocol}//${url.host}`;
    let pathname = url.pathname;

    // redirects.js 中的自定义重定向规则
    const matchedRoute = redirects.find((r) => r.route === pathname);
    if (matchedRoute) {
        const dest = baseUrl + matchedRoute.redirect;
        return redirect(dest, 301);
    }

    // 首页 index.html 重定向到 域名
    if (pathname === '/index.html') {
        return redirect(baseUrl + '/', 301);
    }

    // 首页 / 不处理,保持原样
    if (pathname === '/') {
        return context.next();
    }

    // /path/index.html 重定向到 /path/(带斜杠)
    if (pathname.endsWith('/index.html')) {
        const newPath = pathname.slice(0, -10);
        return redirect(baseUrl + newPath, 301);
    }

    // 带后缀的路径不处理(静态资源)
    if (/\.\w+$/.test(pathname)) {
        return context.next();
    }

    // /path 重定向到 /path/
    if (!pathname.endsWith("/")) {
        return redirect(baseUrl + pathname + "/", 301);
    }

    // 其他请求交给 EdgeOne 处理
    return context.next();
}

// 匹配所有路由
export const config = {
    matcher: ["/:path*"],
};

以上代码做了基本的网址规范化处理,还支持redirects.js配置URL重定向:

export default [
    { route: '/1.html', redirect: '/post/wdcp-v2-upgrade-v3-tutorial/' },
    {......}
];
  • route:需要重定向的路径;
  • redirect:目标路径。

使用中间件会消耗 EdgeOne Pages 函数配额,免费版配额如下:

  • Edge Functions 请求数:300万/月;
  • Edge Functions CPU 时间:300万毫秒/月。

背字根博客页面简单,由Hugo生成全静态页面,单页面请求数在10个左右。监测EdgeOne的消耗,Edge Functions 请求数大概50/PV,是页面真实请求数的5倍左右。Edge Functions CPU 时间160毫秒/PV左右。

所以,别看免费配额有几百万,实际上也就只够500PV/日左右。

根据官方客服描述,5月份EdgeOne会有一次大更新,届时或许可以像Azure Static Web App那样,只需在edgeone.json一个参数便能实现网址规范化。

AI大语言模型