如何在Next.js中为动态路线设置后备重定向?

发布于 2025-02-06 15:18:54 字数 1061 浏览 0 评论 0原文

我使用此文件夹结构为我的博客有一条嵌套,动态的路线:

/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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文