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

Next.js 14使用next-intl调整路由结构可行性咨询

可行,以下是实现步骤及代码调整方案

1. 自定义中间件的Locale提取逻辑

默认的next-intl中间件会从路径开头提取locale,要适配新路径结构/[business_slug]/[locale]/...,需要通过localeExtractor函数自定义locale的提取规则,同时可添加旧路径重定向逻辑兼容历史访问。

修改后的中间件代码:

import createMiddleware from "next-intl/middleware";
import { locales, defaultLocale } from "./configs/next-intl";

export default createMiddleware({
  locales,
  defaultLocale,
  // 自定义提取locale的逻辑
  localeExtractor: (req) => {
    const pathSegments = req.nextUrl.pathname.split('/').filter(Boolean);
    
    // 处理旧路径重定向(可选,若需要兼容/[locale]/[business_slug]/...)
    if (pathSegments.length >= 2 && locales.includes(pathSegments[0])) {
      const [oldLocale, businessSlug, ...rest] = pathSegments;
      const newPath = `/${businessSlug}/${oldLocale}/${rest.join('/')}`;
      return Response.redirect(new URL(newPath, req.nextUrl));
    }

    // 从路径第二个分段提取locale
    if (pathSegments.length >= 2 && locales.includes(pathSegments[1])) {
      return pathSegments[1];
    }

    // 若未匹配到,返回默认locale
    return defaultLocale;
  }
});

export const config = {
  matcher: ["/((?!api|_next|_vercel|.*\\..*).*)"]
};

2. 调整路由文件夹结构

根据新的路径顺序调整你的路由目录(以App Router为例,Pages Router逻辑类似):

app/
├─ [business_slug]/
│  ├─ [locale]/
│  │  ├─ page.jsx          # 对应 /[business_slug]/[locale]/
│  │  ├─ about/
│  │  │  └─ page.jsx      # 对应 /[business_slug]/[locale]/about
│  │  └─ layout.jsx        # 可选,为该层级添加布局
└─ layout.jsx              # 根布局

3. 页面组件中获取参数

在页面组件中可以通过params获取business_slug和locale:

// app/[business_slug]/[locale]/page.jsx
export default function HomePage({ params }) {
  const { business_slug, locale } = params;
  
  return (
    <div>
      <h1>商家:{business_slug}</h1>
      <p>当前语言:{locale}</p>
    </div>
  );
}

4. 调整链接生成逻辑

生成内部链接时,要遵循/[business_slug]/[locale]/...的路径顺序,可结合next-intl的工具函数简化:

import Link from 'next/link';
import { useLocale } from 'next-intl';

// 自定义导航链接组件
export function BusinessNavLink({ businessSlug, href, children }) {
  const locale = useLocale();
  return (
    <Link href={`/${businessSlug}/${locale}${href}`}>
      {children}
    </Link>
  );
}

// 使用示例
<BusinessNavLink businessSlug="coffee-shop" href="/about">关于我们</BusinessNavLink>

若使用next-intl的useRouter进行编程式导航:

import { useRouter } from 'next-intl/router';

const router = useRouter();

// 跳转到商家的关于页面
router.push('/about', { 
  locale: 'zh-CN', 
  business_slug: 'coffee-shop' 
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:07:36