如何在Next.js中为动态路线设置后备重定向?
我使用此文件夹结构为我的博客有一条嵌套,动态的路线:
/pages
/articles
/page
/[...page].js
这会导致网址:
mysite.com/articles/page/1
mysite.com/articles/page/2
如果某人键入以下URL:
mysite.com/articles
mysite.com/articles/page
...我想将它们重定向到mysite.com/articles/page /1
。
我该怎么做?
我认为我可以创建:
/pages
articles.js
/articles
page.js
然后,在这些文件中,我可以使用路由器...
import { useRouter } from 'next/router';
const router = useRouter();
router.push('/articles/page/1');
为每个后备有一个新文件似乎有些过分。我应该改用_MiddleWare.js
文件吗?
import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req, ev) {
const { pathname } = req.nextUrl
if (pathname === '/articles' || pathname === '/articles/page') {
return NextResponse.redirect('/articles/page/1')
}
return NextResponse.next()
}
我还看到可以在next.config.js
中设置重定向,但是我得到的印象更适合301个重定向。
I have a nested, dynamic route for my blog using this folder structure:
/pages
/articles
/page
/[...page].js
This results in URLs like:
mysite.com/articles/page/1
mysite.com/articles/page/2
If someone types one of these URLs:
mysite.com/articles
mysite.com/articles/page
...I'd like to redirect them to mysite.com/articles/page/1
.
How do I do that?
I'm thinking I could create:
/pages
articles.js
/articles
page.js
Then, in these files, I could use the router...
import { useRouter } from 'next/router';
const router = useRouter();
router.push('/articles/page/1');
Having a new file for each fallback seems a little overkill though. Should I use the _middleware.js
file instead?
import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req, ev) {
const { pathname } = req.nextUrl
if (pathname === '/articles' || pathname === '/articles/page') {
return NextResponse.redirect('/articles/page/1')
}
return NextResponse.next()
}
I also see that redirects can be setup in next.config.js
, but I get the impression that is more for 301 redirects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论