如何在Next.js中配置动态basePath与多语言路由重定向规则
Next.js 多语言路由配置方案
要不要创建language文件夹?
别这么干。创建language文件夹会让路由变成/language/en这种层级,和你要的/en、/es根级路径完全不符,纯粹给自己添乱。
直接根级路由+重定向配置(适合自定义需求)
1. 页面文件结构
直接在pages目录下建en和es两个文件夹,每个文件夹里放对应语言的页面文件:
pages/ ├── en/ │ ├── index.tsx // https://localhost:3000/en 对应的首页 │ └── about.tsx // https://localhost:3000/en/about ├── es/ │ ├── index.tsx // https://localhost:3000/es │ └── about.tsx // https://localhost:3000/es/about └── _app.tsx
2. next.config.js 重定向规则配置
在next.config.js里写redirects规则,搞定默认跳转和无效路径重定向:
/** @type {import('next').NextConfig} */ const nextConfig = { async redirects() { return [ // 访问根路径直接跳转到/en { source: '/', destination: '/en', permanent: true, }, // 所有非/en、非/es的路径,都重定向到/en对应的路径;如果/en下没这个页面,就跳/en首页 { source: '/:path((?!en|es).*)', destination: '/en/:path', permanent: true, }, // 处理/en或/es下的404情况:如果访问/en/xxx不存在,跳回/en首页 { source: '/en/:path*', destination: '/en', permanent: true, has: [{ type: 'missing', path: '/en/:path*' }], }, { source: '/es/:path*', destination: '/es', permanent: true, has: [{ type: 'missing', path: '/es/:path*' }], }, ]; }, }; module.exports = nextConfig;
3. 语言切换逻辑
页面里用useRouter钩子就能轻松实现语言切换:
import { useRouter } from 'next/router'; export default function Home() { const router = useRouter(); const currentLang = router.pathname.split('/')[1]; const switchLang = (targetLang: string) => { // 替换路径里的语言前缀 const newPath = router.pathname.replace(`/${currentLang}`, `/${targetLang}`); router.push(newPath); }; return ( <div> <button onClick={() => switchLang('es')}>切换到西班牙语</button> <button onClick={() => switchLang('en')}>切换到英语</button> {/* 页面内容 */} </div> ); }
更省心的替代方案:用Next.js内置国际化路由
Next.js自带多语言路由支持,官方维护更靠谱,步骤如下:
1. next.config.js 配置i18n
/** @type {import('next').NextConfig} */ const nextConfig = { i18n: { locales: ['en', 'es'], // 支持的语言列表 defaultLocale: 'en', // 默认语言,访问根路径会自动跳/en localeDetection: false, // 关掉浏览器语言自动检测,强制用路由里的语言 }, }; module.exports = nextConfig;
2. 页面结构
不用建en/es文件夹,直接在pages下写通用页面,Next.js会自动处理路由:
- 访问
/→ 自动重定向到/en - 访问
/es→ 加载对应语言的页面 - 访问
/about→ 自动跳/en/about,访问/es/about→ 加载西班牙语的about页面
3. 多语言内容管理
可以配合next-i18next库,把翻译文本存在单独的json文件里,管理起来更方便。
这种方案比自定义重定向简洁得多,推荐优先用这个。
内容的提问来源于stack exchange,提问作者Gian Grassi
相关产品推荐
相关产品推荐

