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

NextJS配置中Rewrite规则失效问题求助

问题分析与解决方案

你的Rewrite规则失效的核心原因是:当前规则/:articles/:slug/:id/lite/仅能匹配固定4段路径的URL(例如/article/trending/xxx/lite/),但失效的URL包含5段路径(/article/trending/trending-globally/xxx/lite/),其中:articles和:slug都只能匹配单个路径段,无法覆盖多段前置路径的场景。

修复方案

使用正则捕获组来匹配任意数量的前置路径段,修改next.config.js中的rewrites规则如下:

async rewrites() {
  return [
    {
      // 用 (.*) 捕获 /lite/ 之前的所有路径内容(支持任意段数)
      source: '/(.*)/:id/lite/',
      // $1 对应正则捕获的前置路径,保留原有结构后添加 amp 参数
      destination: '/$1/:id/?amp=1',
    }
  ];
},

如果需要兼容末尾不带斜杠的URL,可以调整source为:

source: '/(.*)/:id/lite/?',

验证效果

  • 对于URL https://localhost:3000/article/trending/us-man-witnesses-his-kidney-transplant-procedure-indian-origin-surgeon-viral-photos-9415947/lite/:
    正则捕获组(.*)会匹配article/trending,最终重写为/article/trending/us-man-witnesses-his-kidney-transplant-procedure-indian-origin-surgeon-viral-photos-9415947/?amp=1,符合预期。
  • 对于URL https://localhost:3000/article/trending/trending-globally/us-man-witnesses-his-kidney-transplant-procedure-indian-origin-surgeon-viral-photos-9415947/lite/:
    正则捕获组(.*)会匹配article/trending/trending-globally,最终重写为/article/trending/trending-globally/us-man-witnesses-his-kidney-transplant-procedure-indian-origin-surgeon-viral-photos-9415947/?amp=1,规则生效。

内容的提问来源于stack exchange,提问作者Ashok Kumar Panthri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:45:03