如何在使用NextJS重定向后删除查询参数



在NextJS中,如何使用重定向将类似/page?foo=bar的URL转换为/page/bar

我读过https://nextjs.org/docs/api-reference/next.config.js/redirects但找不到解决方案。

我今天拥有的是:

{
source: '/page',
has: [
{ 
type: 'query',
key: 'foo'
}
],
destination: '/page/:foo',
permanent: true
}

而使CCD_ 3变为CCD_。

如何删除查询?

编辑:

所以我意识到,这对Netlify根本不起作用。

我试着跟随https://docs.netlify.com/routing/redirects/但我对查询参数的保留也有同样的问题。

您可以使用中间件。

只需自己解析查询参数并添加重定向即可。

将文件_middleware.ts存储在页面目录下:

export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;

if (// Your-thing ) 
return NextResponse.redirect(//Your-url);
return NextResponse.next();
}  

也许有另一种方式,我不知道,但这并不重要。

至少在使用Vercel时,您可以通过在destination中重复has中的参数而将其存档,但将值保留为空。

例如:

{
source: '/page',
has: [
{ 
type: 'query',
key: 'foo'
}
],
destination: '/page/:foo?foo=',
permanent: true
}

destination中已经存在的参数将不会被复制,destination中具有空值的参数将被完全删除。

最新更新