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

如何移除Next.js(App Router)默认语言的URL前缀?

移除Next.js App Router多语言默认语言的URL前缀

1. 修改Next.js配置文件

在next.config.js中添加prefixDefaultLocale: false,该配置会让默认语言(en)不再显示URL前缀:

module.exports = {
  i18n: {
    locales: ['en', 'fa'],
    defaultLocale: 'en',
    prefixDefaultLocale: false, // 关键配置:移除默认语言的URL前缀
  },
}

2. 调整路由结构

  • 将原/src/app/[lang]/page.js的内容迁移到根目录的/src/app/page.js,用于处理默认语言(en)的路由请求
  • 保留/src/app/[lang]/page.js,用于处理非默认语言(fa)的路由请求

3. 统一字典文件的位置与调用逻辑

把原/src/app/[lang]/dictionaries.js移动到/src/app/dictionaries.js,确保两个路由页面都能正确导入:

import 'server-only'

const dictionaries = {
  en: () => import('./dictionaries/en.json').then((module) => module.default),
  fa: () => import('./dictionaries/fa.json').then((module) => module.default),
}

export const getDictionary = async (locale) => dictionaries[locale]()

根目录页面(/src/app/page.js)

通过请求头获取当前语言环境,加载对应字典:

import { getDictionary } from './dictionaries'
import { headers } from 'next/headers'

export default async function Page() {
  const locale = headers().get('next-locale') || 'en'
  const dict = await getDictionary(locale)
  
  return (
    <>
      <button>{dict.products.cart}</button>
    </>
  )
}

多语言路由页面(/src/app/[lang]/page.js)

直接从路由参数获取语言标识,加载对应字典:

import { getDictionary } from '../dictionaries'

export default async function Page({ params: { lang } }) {
  const dict = await getDictionary(lang)
  
  return (
    <>
      <button>{dict.products.cart}</button>
    </>
  )
}

4. 适配语言切换逻辑

如果需要语言切换按钮,使用客户端组件实现,确保切换后路由符合预期:

'use client'
import { useRouter, useLocale } from 'next/navigation'

export default function LanguageSwitcher() {
  const router = useRouter()
  const currentLocale = useLocale()

  const switchLanguage = (newLocale) => {
    const pathname = window.location.pathname
    // 切换路由:默认语言移除前缀,非默认语言添加对应前缀
    const targetPath = newLocale === 'en' 
      ? pathname.replace(/^\/fa/, '')
      : `/fa${pathname}`
    router.push(targetPath)
  }

  return (
    <div>
      <button onClick={() => switchLanguage('en')}>English</button>
      <button onClick={() => switchLanguage('fa')}>فارسی</button>
    </div>
  )
}

5. 链接跳转注意事项

使用next/link时,传入locale参数确保生成正确的路由:

import Link from 'next/link'
import { useLocale } from 'next/navigation'

export default function NavLink() {
  const locale = useLocale()
  return (
    <Link href="/article" locale={locale}>
      Article
    </Link>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:35:35