跳到内容

如何在 Next.js 中处理重定向

在 Next.js 中有几种方法可以处理重定向。本页面将介绍每种可用选项、用例以及如何管理大量重定向。

API目的位置状态码
useRouter执行客户端导航组件不适用
next.config.js 中的 redirects根据路径重定向传入请求next.config.js 文件307(临时)或 308(永久)
NextResponse.redirect根据条件重定向传入请求代理任意

useRouter() hook

如果您需要在组件内部进行重定向,可以使用 useRouter hook 的 push 方法。例如:

app/page.tsx
import { useRouter } from 'next/router'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.push('/dashboard')}>
      Dashboard
    </button>
  )
}

须知:

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

有关更多信息,请参阅 useRouter API 参考

next.config.js 中的 redirects

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

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

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

next.config.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 参考

须知:

  • redirects 可以使用 permanent 选项返回 307(临时重定向)或 308(永久重定向)状态码。
  • redirects 在平台上可能有数量限制。例如,在 Vercel 上,重定向的数量限制为 1,024 个。要管理大量重定向(1000+),请考虑使用 Proxy 创建自定义解决方案。有关更多信息,请参阅大规模管理重定向
  • redirects 在 Proxy 之前运行。

Proxy 中的 NextResponse.redirect

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

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

proxy.ts
import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'
 
export function proxy(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*',
}

须知:

  • Proxy 在 next.config.js 中的 redirects 之后运行,并在渲染之前运行。

有关更多信息,请参阅 Proxy 文档。

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

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

为此,您需要考虑

  1. 创建和存储重定向映射。
  2. 优化数据查找性能。

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

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

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

考虑以下数据结构

{
  "/old": {
    "destination": "/new",
    "permanent": true
  },
  "/blog/post-old": {
    "destination": "/blog/post-new",
    "permanent": true
  }
}

Proxy 中,您可以从数据库(例如 Vercel 的 Edge ConfigRedis)中读取,并根据传入请求重定向用户

proxy.ts
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/edge-config'
 
type RedirectEntry = {
  destination: string
  permanent: boolean
}
 
export async function proxy(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. 优化数据查找性能

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

  • 使用针对快速读取优化的数据库
  • 使用数据查找策略,例如布隆过滤器,以在读取更大的重定向文件或数据库之前有效地检查重定向是否存在。

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

如果存在,将请求转发到 API Routes,它将检查实际文件并将用户重定向到适当的 URL。这避免了将大型重定向文件导入到 Proxy 中,这会减慢每个传入请求。

proxy.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 proxy(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 路由中

pages/api/redirects.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)
}

须知

  • 要生成布隆过滤器,您可以使用像 bloom-filters 这样的库。
  • 您应该验证对您的路由处理程序发出的请求,以防止恶意请求。