Next.js使用next-intl本地化:移除默认语言URL前缀问题
问题
首次在Next.js中使用next-intl实现本地化,功能正常,但URL不符合预期:希望默认语言“cs”对应的URL不带语言标识(即http://localhost:3000/),但系统总是自动跳转到带cs的URL(http://localhost:3000/cs)。尝试过从middleware.ts的matcher中移除“cs”,也尝试在i18n.ts中添加localeDetection: false,均无效。
附上当前代码:
middleware.ts
export default createMiddleware({ // A list of all locales that are supported locales: ["cs", "en"], // Used when no locale matches defaultLocale: "cs", }); export const config = { // Match only internationalized pathnames matcher: ["/", "/(cs|en)/:path*"], };
i18n.ts
import { notFound } from "next/navigation"; import { getRequestConfig } from "next-intl/server"; // Can be imported from a shared config const locales = ["cs"]; export default getRequestConfig(async ({ locale }) => { // Validate that the incoming `locale` parameter is valid // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any if (!locales.includes(locale as any)) notFound(); return { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access messages: (await import(`/i18n/${locale}.json`)).default, }; });
解决方案
要实现默认语言URL不带语言标识,需调整createMiddleware的配置并修正i18n.ts中的语言列表:
1. 更新 middleware.ts
添加localePrefix: 'as-needed'配置,该选项会让默认语言的URL不显示语言标识,仅非默认语言路径才会带上语言前缀:
export default createMiddleware({ locales: ["cs", "en"], defaultLocale: "cs", // 配置默认语言不显示locale前缀 localePrefix: 'as-needed' }); export const config = { matcher: ["/", "/(cs|en)/:path*"], };
2. 修正 i18n.ts 中的 locales 数组
当前locales数组仅包含"cs",与实际支持的cs、en两种语言不符,会导致访问英文路径时触发404,需修正为:
import { notFound } from "next/navigation"; import { getRequestConfig } from "next-intl/server"; // 包含所有支持的语言 const locales = ["cs", "en"]; export default getRequestConfig(async ({ locale }) => { if (!locales.includes(locale as any)) notFound(); return { messages: (await import(`/i18n/${locale}.json`)).default, }; });
补充说明
localePrefix支持三个可选值:'always':所有URL都强制带上语言标识(next-intl默认行为)'as-needed':仅非默认语言的URL显示语言标识,默认语言路径保持无前缀'never':所有URL都不带语言标识,需依赖Cookie、Header等其他方式检测用户语言
- 无需修改原有
matcher配置,middleware会自动匹配并处理不带语言标识的默认语言路径。
内容的提问来源于stack exchange,提问作者Dima Malko
相关产品推荐
相关产品推荐

