You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js基于用户国家跳转时出现err_too_many_redirects问题求助

解决Next.js中间件重定向循环(err_too_many_redirects)问题

你的代码触发无限重定向的核心原因是:重定向后的路径依然会被中间件匹配。比如用户被重定向到/egypt/xxx后,中间件会再次触发,检测到用户来自埃及后又将路径改为/egypt/egypt/xxx,反复循环导致浏览器报错。

修复方案

1. 提前判断路径是否已包含国家前缀

在重定向逻辑前,先检查当前请求路径是否已经是目标国家的前缀,避免重复重定向:

type Middleware = (req: NextRequest) => Promise<NextResponse>;

export const middleware: Middleware = async (req) => {
    // 路径已包含埃及前缀,直接放行
    if (req.nextUrl.pathname.startsWith('/egypt')) {
        return NextResponse.next();
    }

    const response = await fetch(`http://ip-api.com/json`);
    const data = await response.json();

    if (data.country === "Egypt") {
        console.log('Egypt')
        const newPath = `/egypt${req.nextUrl.pathname}${req.nextUrl.search}`;
        const newUrl = new URL(newPath, req.url);

        return NextResponse.redirect(newUrl, { status: 301 });
    } else {
        return NextResponse.next();
    }
};

export const config = {
    matcher: [
        "/((?!api|static|favicon.ico|_next|_next/image|images).*)"
    ]
};

2. 优化matcher规则(可选)

如果国家前缀是固定的(比如/egypt、/us),可以直接在matcher里排除这些路径,从根源避免中间件处理重定向后的请求:

export const config = {
    matcher: [
        "/((?!api|static|favicon.ico|_next|_next/image|images|egypt|us).*)"
    ]
};

3. 缓存IP查询结果(性能优化)

每次触发中间件都调用IP查询接口会影响性能,建议用Cookie缓存用户国家信息,避免重复请求:

type Middleware = (req: NextRequest) => Promise<NextResponse>;

export const middleware: Middleware = async (req) => {
    if (req.nextUrl.pathname.startsWith('/egypt')) {
        return NextResponse.next();
    }

    // 优先从Cookie获取缓存的国家信息
    const cachedCountry = req.cookies.get('user-country')?.value;
    let country = cachedCountry;

    if (!country) {
        const response = await fetch(`http://ip-api.com/json`);
        const data = await response.json();
        country = data.country;
    }

    if (country === "Egypt") {
        const newPath = `/egypt${req.nextUrl.pathname}${req.nextUrl.search}`;
        const newUrl = new URL(newPath, req.url);
        const redirectResponse = NextResponse.redirect(newUrl, { status: 301 });
        // 设置Cookie缓存国家信息,有效期1天
        redirectResponse.cookies.set('user-country', 'Egypt', { maxAge: 86400 });
        return redirectResponse;
    } else {
        return NextResponse.next();
    }
};

内容的提问来源于stack exchange,提问作者xerka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:25:01