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

Next.js带查询参数的本地化重写触发浏览器重载与脚本加载错误

问题根因

该现象由两个配置疏漏共同导致:

  1. Next.js 客户端路由会优先匹配 pages 目录下的物理文件,你给 <Link> 传的 href 是本地化路径(如 /nl/winkels/[id]),pages 下不存在对应文件,路由匹配失败就会触发全页重载,回退到服务端走 rewrites 规则
  2. 你当前配置的 rewrites 规则没有匹配带 locale 前缀的路径,仅能匹配路径完全等于 /winkels/xxx 的请求,实际业务请求路径前缀带 /nl/ 或 /fr/,规则无法生效

解决方案

<Link> 组件的 href 属性传内部实际的页面路径(对应 pages 目录下的文件路径),as 属性传要显示在地址栏的本地化路径,Next.js 会直接走客户端路由,不需要等 rewrites 匹配:

<Link
  href={{
    pathname: `/${locale}/stores/[id]`,
    query: { id: name },
  }}
  // as属性传入拼接完成的本地化路径,示例值:/nl/winkels/lommel
  as={getLocalizedPath(pathnames.STOREFINDER_DETAIL, locale, { id: name })}
  passHref
>
  <Button className="store-info-card-cta" color="secondary">
    {formatMessage({ id: 'store_finder_search_result_details' })}
  </Button>
</Link>

其中 getLocalizedPath 只需直接返回拼接好的本地化字符串路径即可。

方案2:修正 rewrites 规则适配 locale 前缀

如果你不想调整 Link 写法,只需扩展 rewrites 规则的匹配范围,覆盖带 locale 前缀的路径:

// next.config.js 中rewrites修改为
async rewrites() {
  return [
    {
      source: '/:locale(nl|fr)/winkels',
      destination: '/:locale/stores',
    },
    {
      source: '/:locale(nl|fr)/magasins',
      destination: '/:locale/stores',
    },
    {
      source: '/:locale(nl|fr)/winkels/:id',
      destination: '/:locale/stores/:id',
    },
    {
      source: '/:locale(nl|fr)/magasins/:id',
      destination: '/:locale/stores/:id',
    },  
  ]
}

修改后重启 Next.js 服务即可生效。

方案3:使用 Next.js 内置 i18n 路由(推荐,Next.js 10+支持)

直接在 next.config.js 中配置 i18n 规则,Next.js 会自动处理 locale 前缀逻辑,不需要手动写大量重复的 rewrites 规则:

// next.config.js 新增i18n配置
module.exports = {
  i18n: {
    locales: ['nl', 'fr'],
    defaultLocale: 'nl',
  },
  // 剩余rewrites规则不需要额外加locale前缀匹配
}

配置完成后原有 Link 写法可直接复用,不会再出现全页重载问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:18:04