如何在Next.js中配置i18n路由使用斜杠分隔国家语言而非短横线
实现方案
该需求完全可以实现,核心通过修改Next.js路由配置、补充重写规则、自定义locale解析逻辑三个步骤即可完成,无需调整现有next-i18next.config.js的基础配置。
步骤1:修改next.config.js配置
在Next.js配置文件中添加重写规则,把新格式的路由映射到原有i18n可识别的locale格式路径,可选添加重定向规则兼容旧格式路由:
// next.config.js const { i18n } = require('./next-i18next.config'); module.exports = { i18n: { ...i18n, localeDetection: false, }, // 路由重写规则,完成新旧路径的内部映射 async rewrites() { return [ { source: '/:country/:language/:path*', destination: '/:language-:country/:path*', }, { source: '/:country/:language', destination: '/:language-:country', }, ]; }, // 可选:旧格式路由自动跳转到新格式,SEO友好 async redirects() { return [ { source: '/:language-:country/:path*', destination: '/:country/:language/:path*', permanent: true, }, { source: '/:language-:country', destination: '/:country/:language', permanent: true, } ]; } };
注意:不需要兼容旧路由的话可以直接删除redirects配置项
步骤2:自定义locale解析逻辑
因为路由结构变更,需要手动从URL路径中提取国家、语言参数,拼接成你现有配置中支持的locale格式:
// 页面层级示例:在getServerSideProps中处理locale解析 import { serverSideTranslations } from 'next-i18next/serverSideTranslations'; import { i18n } from '../next-i18next.config'; export async function getServerSideProps(ctx) { const { params } = ctx; const { country, language } = params; const parsedLocale = `${language}-${country}`; // 校验解析后的locale是否合法,不合法则走默认值 const currentLocale = i18n.locales.includes(parsedLocale) ? parsedLocale : i18n.defaultLocale; return { props: { ...(await serverSideTranslations(currentLocale, ['common'])), }, }; }
如果使用Next.js 13+ App Router,可以把这部分逻辑放到middleware中全局处理,无需每个页面单独配置。
步骤3:调整站内链接生成规则
后续生成跳转链接时直接按照/{country}/{language}/目标路径的格式生成即可,重写规则会自动完成内部路由映射,原有i18n的多语言加载、fallback逻辑都可以正常生效。
如果是静态导出场景,只需要调整构建路径规则,按照/{country}/{language}的目录结构生成静态文件即可,无需额外修改配置。
内容的提问来源于stack exchange,提问作者Mahmoud Ashraf
相关产品推荐
相关产品推荐

