Skip to content

重定向

¥Redirecting

你可以通过多种方式处理 Next.js 中的重定向。本页将介绍每个可用选项、用例以及如何管理大量重定向。

¥There are a few ways you can handle redirects in Next.js. This page will go through each available option, use cases, and how to manage large numbers of redirects.

API目的哪里状态代码
useRouter执行客户端导航组件N/A
redirectsnext.config.js根据路径重定向传入请求next.config.js 文件307(临时)或 308(永久)
NextResponse.redirect根据条件重定向传入请求中间件任何

useRouter()

¥useRouter() hook

如果你需要在组件内部重定向,可以使用 useRouter 钩子中的 push 方法。例如:

¥If you need to redirect inside a component, you can use the push method from the useRouter hook. For example:

tsx
import { useRouter } from 'next/router'

export default function Page() {
  const router = useRouter()

  return (
    <button type="button" onClick={() => router.push('/dashboard')}>
      Dashboard
    </button>
  )
}

需要了解:

¥Good to know:

  • 如果你不需要以编程方式导航用户,则应使用 <Link> 组件。

    ¥If you don't need to programmatically navigate a user, you should use a <Link> component.

请参阅 useRouter API 参考 了解更多信息。

¥See the useRouter API reference for more information.

redirectsnext.config.js

¥redirects in next.config.js

next.config.js 文件中的 redirects 选项允许你将传入请求路径重定向到不同的目标路径。当你更改页面的 URL 结构或拥有提前已知的重定向列表时,这非常有用。

¥The redirects option in the next.config.js file allows you to redirect an incoming request path to a different destination path. This is useful when you change the URL structure of pages or have a list of redirects that are known ahead of time.

redirects 支持 path标头、cookie 和查询匹配,使你可以灵活地根据传入请求重定向用户。

¥redirects supports path, header, cookie, and query matching, giving you the flexibility to redirect users based on an incoming request.

要使用 redirects,请将选项添加到 next.config.js 文件中:

¥To use redirects, add the option to your next.config.js file:

ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  async redirects() {
    return [
      // Basic redirect
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
      // Wildcard path matching
      {
        source: '/blog/:slug',
        destination: '/news/:slug',
        permanent: true,
      },
    ]
  },
}

export default nextConfig

请参阅 redirects API 参考 了解更多信息。

¥See the redirects API reference for more information.

需要了解:

¥Good to know:

  • redirects 可以使用 permanent 选项返回 307(临时重定向)或 308(永久重定向)状态代码。

    ¥redirects can return a 307 (Temporary Redirect) or 308 (Permanent Redirect) status code with the permanent option.

  • redirects 可能对平台有限制。例如,在 Vercel 上,重定向限制为 1,024 个。要管理大量重定向 (1000+),请考虑使用 中间件 创建自定义解决方案。查看 大规模管理重定向 了解更多信息。

    ¥redirects may have a limit on platforms. For example, on Vercel, there's a limit of 1,024 redirects. To manage a large number of redirects (1000+), consider creating a custom solution using Middleware. See managing redirects at scale for more.

  • redirects 在中间件之前运行。

    ¥redirects runs before Middleware.

中间件中的 NextResponse.redirect

¥NextResponse.redirect in Middleware

中间件允许你在请求完成之前运行代码。然后,根据传入请求,使用 NextResponse.redirect 重定向到不同的 URL。如果你想根据条件(例如身份验证、会话管理等)重定向用户或有 大量重定向

¥Middleware allows you to run code before a request is completed. Then, based on the incoming request, redirect to a different URL using NextResponse.redirect. This is useful if you want to redirect users based on a condition (e.g. authentication, session management, etc) or have a large number of redirects.

例如,如果用户未通过身份验证,则将用户重定向到 /login 页面:

¥For example, to redirect the user to a /login page if they are not authenticated:

ts
import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'

export function middleware(request: NextRequest) {
  const isAuthenticated = authenticate(request)

  // If the user is authenticated, continue as normal
  if (isAuthenticated) {
    return NextResponse.next()
  }

  // Redirect to login page if not authenticated
  return NextResponse.redirect(new URL('/login', request.url))
}

export const config = {
  matcher: '/dashboard/:path*',
}

需要了解:

¥Good to know:

  • 中间件在 redirects 之后、next.config.js 中、渲染之前运行。

    ¥Middleware runs after redirects in next.config.js and before rendering.

有关详细信息,请参阅 中间件 文档。

¥See the Middleware documentation for more information.

大规模管理重定向(高级)

¥Managing redirects at scale (advanced)

要管理大量重定向(1000+),你可以考虑使用中间件创建自定义解决方案。这允许你以编程方式处理重定向,而无需重新部署应用。

¥To manage a large number of redirects (1000+), you may consider creating a custom solution using Middleware. This allows you to handle redirects programmatically without having to redeploy your application.

为此,你需要考虑:

¥To do this, you'll need to consider:

  1. 创建并存储重定向映射。

    ¥Creating and storing a redirect map.

  2. 优化数据查找性能。

    ¥Optimizing data lookup performance.

Next.js 示例:请参阅我们的 带有布隆过滤器的中间件 示例,了解以下建议的实现情况。

¥Next.js Example: See our Middleware with Bloom filter example for an implementation of the recommendations below.

1. 创建并存储重定向映射

¥ Creating and storing a redirect map

重定向映射是可以存储在数据库(通常是键值存储)或 JSON 文件中的重定向列表。

¥A redirect map is a list of redirects that you can store in a database (usually a key-value store) or JSON file.

考虑以下数据结构:

¥Consider the following data structure:

中间件 中,你可以从 Vercel 的 边缘配置Redis 等数据库中读取数据,并根据传入的请求重定向用户:

¥In Middleware, you can read from a database such as Vercel's Edge Config or Redis, and redirect the user based on the incoming request:

ts
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config'

type RedirectEntry = {
  destination: string
  permanent: boolean
}

export async function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname
  const redirectData = await get(pathname)

  if (redirectData && typeof redirectData === 'string') {
    const redirectEntry: RedirectEntry = JSON.parse(redirectData)
    const statusCode = redirectEntry.permanent ? 308 : 307
    return NextResponse.redirect(redirectEntry.destination, statusCode)
  }

  // No redirect found, continue without redirecting
  return NextResponse.next()
}

2. 优化数据查找性能

¥ Optimizing data lookup performance

为每个传入请求读取大型数据集可能既缓慢又昂贵。有两种方法可以优化数据查找性能:

¥Reading a large dataset for every incoming request can be slow and expensive. There are two ways you can optimize data lookup performance:

  • 使用针对快速读取进行了优化的数据库

    ¥Use a database that is optimized for fast reads

  • 在读取较大的重定向文件或数据库之前,使用数据查找策略(例如 布隆过滤器)有效地检查重定向是否存在。

    ¥Use a data lookup strategy such as a Bloom filter to efficiently check if a redirect exists before reading the larger redirects file or database.

考虑到前面的示例,你可以将生成的布隆过滤器文件导入到中间件中,然后检查传入请求路径名是否存在于布隆过滤器中。

¥Considering the previous example, you can import a generated bloom filter file into Middleware, then, check if the incoming request pathname exists in the bloom filter.

如果成功,则将请求转发到 API 路由API 路由 将检查实际文件并将用户重定向到相应的 URL。这可以避免将大型重定向文件导入中间件,这会减慢每个传入请求的速度。

¥If it does, forward the request to a API Routes which will check the actual file and redirect the user to the appropriate URL. This avoids importing a large redirects file into Middleware, which can slow down every incoming request.

ts
import { NextResponse, NextRequest } from 'next/server'
import { ScalableBloomFilter } from 'bloom-filters'
import GeneratedBloomFilter from './redirects/bloom-filter.json'

type RedirectEntry = {
  destination: string
  permanent: boolean
}

// Initialize bloom filter from a generated JSON file
const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter as any)

export async function middleware(request: NextRequest) {
  // Get the path for the incoming request
  const pathname = request.nextUrl.pathname

  // Check if the path is in the bloom filter
  if (bloomFilter.has(pathname)) {
    // Forward the pathname to the Route Handler
    const api = new URL(
      `/api/redirects?pathname=${encodeURIComponent(request.nextUrl.pathname)}`,
      request.nextUrl.origin
    )

    try {
      // Fetch redirect data from the Route Handler
      const redirectData = await fetch(api)

      if (redirectData.ok) {
        const redirectEntry: RedirectEntry | undefined =
          await redirectData.json()

        if (redirectEntry) {
          // Determine the status code
          const statusCode = redirectEntry.permanent ? 308 : 307

          // Redirect to the destination
          return NextResponse.redirect(redirectEntry.destination, statusCode)
        }
      }
    } catch (error) {
      console.error(error)
    }
  }

  // No redirect found, continue the request without redirecting
  return NextResponse.next()
}

然后,在 API 路由中:

¥Then, in the API Route:

ts
import type { NextApiRequest, NextApiResponse } from 'next'
import redirects from '@/app/redirects/redirects.json'

type RedirectEntry = {
  destination: string
  permanent: boolean
}

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const pathname = req.query.pathname
  if (!pathname) {
    return res.status(400).json({ message: 'Bad Request' })
  }

  // Get the redirect entry from the redirects.json file
  const redirect = (redirects as Record<string, RedirectEntry>)[pathname]

  // Account for bloom filter false positives
  if (!redirect) {
    return res.status(400).json({ message: 'No redirect' })
  }

  // Return the redirect entry
  return res.json(redirect)
}

需要了解:

¥Good to know:

  • 要生成布隆过滤器,你可以使用像 bloom-filters 这样的库。

    ¥To generate a bloom filter, you can use a library like bloom-filters.

  • 你应该验证向路由处理程序发出的请求以防止恶意请求。

    ¥You should validate requests made to your Route Handler to prevent malicious requests.