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

Next.js使用route.push切换语言URL时出现无效导航错误

语言切换后URL更新但出现无效导航错误的排查方案

当前网站URL为http://localhost:3000/entreposage-mobile/residentiel/,切换至法语后URL变为http://localhost:3000/fr/entreposage-mobile/residentiel/,但出现无效导航错误,错误截图如下:

切换语言后URL更新但出现错误

以下是常见问题排查及解决方法:

  • 路由配置缺失
    检查前端框架的路由规则(如React Router、Next.js等),确认是否为带语言前缀的路径配置了正确的路由映射。以Next.js为例,需在next.config.js中确保i18n配置包含目标语言,且路由能正确匹配前缀路径:

    module.exports = {
      i18n: {
        locales: ['en', 'fr'],
        defaultLocale: 'en',
      },
    }
    
  • 页面文件结构不匹配
    若为静态站点,需确认法语版本的页面文件是否存在于/fr/entreposage-mobile/residentiel/对应的目录下,或配置了正确的重定向规则,将带语言前缀的路径指向对应语言的页面资源。

  • 语言切换逻辑的URL拼接错误
    检查语言切换函数的代码,确保URL拼接时正确处理原路径结构,避免层级错误。示例修正代码:

    const switchLanguage = (lang) => {
      const currentPath = window.location.pathname;
      // 移除已存在的语言前缀
      const cleanedPath = currentPath.replace(/^\/[a-z]{2}\//, '/');
      // 拼接新的带语言前缀路径
      const newPath = `/${lang}${cleanedPath}`;
      window.location.href = newPath;
    }
    
  • 服务器重写规则未配置
    若使用Nginx或Apache等服务器,需配置重写规则,确保带语言前缀的路径能被正确解析到应用入口文件。以Nginx为例:

    location / {
      try_files $uri $uri/ /index.html;
    }
    # 处理带语言前缀的路径
    location ~ ^/[a-z]{2}/ {
      try_files $uri $uri/ /index.html;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:50:28