Next.js Rewrites问题:第二条重写规则无法生效
问题原因与解决方案
问题出在/app路由的重写规则destination路径错误,导致指向了不存在的文件路径。
你的文件结构中,frontend和backend都在src/app目录下,对应的实际路由路径是/frontend/hello和/backend/hello。而你原来的/app重写规则把请求指向了/app/frontend/:path*,这会让Next.js去查找src/app/app/frontend/hello/page.tsx——这个路径根本不存在,所以返回404。
至于/backend的规则看似正常,其实是因为/backend/hello本身就是有效路由(直接对应src/app/backend/hello/page.tsx),重写规则根本没起作用。
修改后的配置
把next.config.mjs中的重写规则调整如下:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/app/:path*', destination: '/frontend/:path*', }, // 以下backend规则可移除,因为原路由已直接生效 // { // source: '/backend/:path*', // destination: '/app/backend/:path*', // }, ] } }; export default nextConfig;
修改后,访问localhost:3000/app/hello时,会被正确重写到/frontend/hello,对应你已有的src/app/frontend/hello/page.tsx文件,即可正常显示内容。
内容的提问来源于stack exchange,提问作者simon
相关产品推荐
相关产品推荐

