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

Next.js i18n配置:调整URL中语言代码的位置

Next.js i18n 路由自定义:将语言代码放在路由中间的实现方案

Next.js 原生的i18n路由配置无法直接实现将语言代码置于路由中间(如/subroute/{language-code}/my-page)的需求,但通过Middleware可以完全满足,且能精准控制仅对指定页面生效。

实现步骤

1. 调整Next.js i18n基础配置

首先禁用Next.js自动添加语言前缀的跳转逻辑,确保我们能完全自定义路由规则:

// next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'zh', 'es'], // 你的语言列表
    defaultLocale: 'en',
    localeDetection: false, // 禁止自动检测浏览器语言跳转
  },
}

2. 编写Middleware实现路由重写与重定向

在项目根目录创建middleware.ts(或.js)文件,编写路由处理逻辑,匹配目标路由并调整语言代码位置:

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// 定义需要应用自定义i18n路由的路由前缀
const TARGET_ROUTE_PREFIXES = ['/subroute']

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl

  // 场景1:处理用户访问的 /subroute/en/my-page → 重写为 /en/subroute/my-page
  // 让Next.js的i18n系统能识别到locale参数
  const middleLangPattern = /^\/subroute\/([a-z]{2})\/(.+)$/
  const middleLangMatch = pathname.match(middleLangPattern)
  
  if (middleLangMatch) {
    const [, lang, restPath] = middleLangMatch
    const rewrittenPath = `/${lang}/subroute/${restPath}`
    const rewrittenUrl = new URL(rewrittenPath, request.url)
    return NextResponse.rewrite(rewrittenUrl)
  }

  // 场景2:处理用户访问的 /subroute/my-page → 重定向到默认语言的路径 /subroute/en/my-page
  const needsLangInsert = TARGET_ROUTE_PREFIXES.some(prefix => pathname.startsWith(prefix)) 
    && !pathname.match(/^\/[a-z]{2}\//) // 排除已带语言前缀的路径

  if (needsLangInsert) {
    const defaultLang = 'en'
    const redirectedPath = pathname.replace(/^\/subroute/, `/subroute/${defaultLang}`)
    const redirectedUrl = new URL(redirectedPath, request.url)
    return NextResponse.redirect(redirectedUrl)
  }

  // 非目标路由直接放行
  return NextResponse.next()
}

// 限定Middleware仅对目标路由生效,提升性能
export const config = {
  matcher: ['/subroute/:path*'],
}

3. 页面中获取Locale的方式保持不变

在页面组件中,你依然可以通过useRouter()获取locale,或在getStaticProps/getServerSideProps中接收locale参数,和原生i18n用法一致:

// pages/subroute/[...rest].tsx
import { useRouter } from 'next/router'

export default function SubroutePage() {
  const router = useRouter()
  const { locale } = router
  return <div>当前语言:{locale}</div>
}

关键说明

  • 正则表达式需根据你的实际路由结构调整,确保准确匹配语言代码的位置。
  • 通过matcher配置限定Middleware的作用范围,避免不必要的性能开销。
  • 此方案仅对指定路由生效,其他页面可保持原生i18n路由逻辑(或自定义其他规则)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:30:56