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

Next.js/next-intl默认Locale配置异常:根路径重定向至/en

问题解决:Next-intl 默认Locale下根路径被重定向至带前缀路由

可能原因及修复方案

1. 显式指定localePrefix为'as-needed'

尽管next-intl默认localePrefix值为'as-needed'(默认Locale无需路由前缀),但显式声明可规避版本或隐式配置冲突。修改你的middleware.js:

import createMiddleware from 'next-intl/middleware';

export default createMiddleware({
  locales: ['en', 'ar', 'es'],
  defaultLocale: 'en',
  localeDetection: false,
  localePrefix: 'as-needed' // 新增该行明确配置
});

export const config = {
  matcher: ['/((?!api|_next|.*\\..*).*)']
};

2. 移除Next.js官方i18n配置冲突

next-intl会独立处理国际化路由,若next.config.js中启用了Next.js官方i18n配置,会导致路由规则冲突,需移除:
❌ 需删除的冲突配置示例:

/** @type {import('next').NextConfig} */
const nextConfig = {
  i18n: {
    locales: ['en', 'ar', 'es'],
    defaultLocale: 'en'
  }
};

module.exports = nextConfig;

✅ 正确配置示例(仅保留next-intl相关插件):

const withNextIntl = require('next-intl/plugin')('./i18n.ts'); // 路径根据你的i18n配置文件调整

/** @type {import('next').NextConfig} */
const nextConfig = {};

module.exports = withNextIntl(nextConfig);

3. 清除浏览器缓存或用无痕模式测试

浏览器可能缓存了旧的重定向规则,导致新配置不生效。尝试:

  • 快捷键Ctrl+Shift+Delete清除缓存
  • 使用无痕/隐私窗口访问localhost:3000

4. 验证页面路由结构合规性

确保页面文件结构支持无前缀的默认Locale路由:

  • App Router模式:页面需放在app/[locale]/page.tsx(根路径/会自动匹配默认Locale的页面)
  • Pages Router模式:页面需放在pages/[locale]/index.tsx

若页面直接放在app/page.tsx或pages/index.tsx,next-intl中间件无法正确匹配路由,会触发不必要的重定向。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:16:07