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

Next.js 14不同路由组级别自定义not-found页面失效问题

问题描述

我的Next.js项目采用App Router,文件夹结构如下:

app
├── (app1)
│    └── ekko 
│       ├── layout.tsx
│       ├── not-found.tsx
│       └── page.tsx
│
└── (admin)
│    └── admin
│       ├── layout.tsx
│       ├── not-found.tsx
│       └── page.tsx
│
└── layout.tsx

我在ekko和admin目录下都配置了not-found.tsx,但访问错误路径(比如/admin/whatever)时,并没有渲染对应路由组的自定义404页面,而是显示Next.js的默认404页面。我希望访问/ekko/wrong-params时显示ekko下的自定义404,访问/admin/wrong-params时显示admin下的自定义404。

解决方案

在Next.js的App Router中,not-found.tsx需要被主动触发才会渲染——当某个路由路径没有匹配到任何已定义的路由时,框架会向上查找最近的not-found.tsx,但如果没有对应的捕获路由,就会直接用顶层默认404。要实现分路由组的自定义404,需要给每个需要捕获子路径错误的目录添加catch-all动态路由:

  1. 给ekko目录添加[...catchAll]/page.tsx文件:
// app/(app1)/ekko/[...catchAll]/page.tsx
import { notFound } from 'next/navigation';

export default function CatchAllPage() {
  notFound();
}
  1. 给admin目录添加[...catchAll]/page.tsx文件:
// app/(admin)/admin/[...catchAll]/page.tsx
import { notFound } from 'next/navigation';

export default function CatchAllPage() {
  notFound();
}

这样配置后,当访问/ekko/xxx或/admin/xxx这类未定义的子路径时,catch-all路由会匹配该路径,调用notFound()函数,触发同级的not-found.tsx渲染,从而显示对应路由组的自定义404页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:45:05