我正在尝试进行简单的重写。因此,所有 /app 流量都会重写到 /frontend 文件夹,所有 /backend 流量都会重写到 /backend 文件夹。
如果我启动:localhost:3000/app/hello,则会收到错误 404 然而,如果我启动: localhost:3000/backend/hello
,我不会收到错误 404以下是我在 next.config.mjs 中尝试过的:
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: '/backend/:path*',
destination: '/app/backend/:path*',
},
{
source: '/app/:path*',
destination: '/app/frontend/:path*',
},
]
}
};
export default nextConfig;
我在前端和后端都有 page.tsx 文件:
src pp rontend\hello\page.tsx
export default function World() {
return (
<div>
body
</div>
)
}
src pp ackend\hello\page.tsx
export default function World() {
return (
<div>
body
</div>
)
}
总而言之,第一个后端重写工作完美,而 /app 则不然
如果根目录中有
src
或app
,next将忽略它,检查文件系统后将应用重写功能。
所以基本上你的两个重写目的地都不存在。
localhost:3000/backend/hello
起作用的原因是src\app\backend\hello
处有一个page.tsx,所以重写没有应用。
这应该有效:
async rewrites() {
return [
// looks like backend doesn't need redirect
{
source: '/app/:path*',
destination: '/frontend/:path*', //remove 'app/'
},
]
}
希望这对您有帮助。
这将解决您的问题:
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
// Your backend rewrite part
{
source: '/:path*',
destination: '/frontend/:path*',
},
]
}
};
现在尝试点击 localhost:3000/hello,它会将您重定向到预期的路径 localhost:3000/frontend/hello。