跳到内容

重定向

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

API目的位置状态码
redirect在突变或事件后重定向用户服务器组件、服务器操作、路由处理器307(临时)或 303(服务器操作)
permanentRedirect在突变或事件后重定向用户服务器组件、服务器操作、路由处理器308(永久)
useRouter执行客户端导航客户端组件中的事件处理程序N/A
next.config.js 中的 redirects根据路径重定向传入的请求next.config.js 文件307(临时)或 308(永久)
NextResponse.redirect根据条件重定向传入的请求中间件任何位置

redirect 函数

redirect 函数允许你将用户重定向到另一个 URL。你可以在服务器组件路由处理器服务器操作中调用 redirect

redirect 通常在突变或事件后使用。例如,创建帖子

app/actions.ts
'use server'
 
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
 
export async function createPost(id: string) {
  try {
    // Call database
  } catch (error) {
    // Handle errors
  }
 
  revalidatePath('/posts') // Update cached posts
  redirect(`/post/${id}`) // Navigate to the new post page
}

须知:

  • 默认情况下,redirect 返回 307(临时重定向)状态码。当在服务器操作中使用时,它返回 303(查看其他),这通常用于将 POST 请求的结果重定向到成功页面。
  • redirect 在内部抛出一个错误,因此应该在 try/catch 块之外调用。
  • redirect 可以在客户端组件的渲染过程中调用,但不能在事件处理程序中调用。你可以改用 useRouter 钩子
  • redirect 也接受绝对 URL,可用于重定向到外部链接。
  • 如果你想在渲染过程之前重定向,请使用 next.config.js中间件

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

permanentRedirect 函数

permanentRedirect 函数允许你将用户永久重定向到另一个 URL。你可以在服务器组件路由处理器服务器操作中调用 permanentRedirect

permanentRedirect 通常在更改实体规范 URL 的突变或事件后使用,例如在用户更改用户名后更新用户的个人资料 URL

app/actions.ts
'use server'
 
import { permanentRedirect } from 'next/navigation'
import { revalidateTag } from 'next/cache'
 
export async function updateUsername(username: string, formData: FormData) {
  try {
    // Call database
  } catch (error) {
    // Handle errors
  }
 
  revalidateTag('username') // Update all references to the username
  permanentRedirect(`/profile/${username}`) // Navigate to the new user profile
}

须知:

  • 默认情况下,permanentRedirect 返回 308(永久重定向)状态码。
  • permanentRedirect 也接受绝对 URL,可用于重定向到外部链接。
  • 如果你想在渲染过程之前重定向,请使用 next.config.js中间件

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

useRouter() 钩子

如果你需要在客户端组件的事件处理程序中重定向,可以使用 useRouter 钩子的 push 方法。例如

app/page.tsx
'use client'
 
import { useRouter } from 'next/navigation'
 
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+),请考虑使用中间件创建自定义解决方案。有关更多信息,请参阅大规模管理重定向
  • redirects 在中间件之前运行。

Middleware 中的 NextResponse.redirect

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

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

middleware.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*',
}

须知:

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

有关更多信息,请参阅中间件文档。

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

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

为此,你需要考虑

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

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

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

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

考虑以下数据结构

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

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

middleware.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. 优化数据查找性能

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

  • 使用针对快速读取优化的数据库,例如 Vercel Edge ConfigRedis
  • 使用数据查找策略(例如 Bloom 过滤器)来有效地检查重定向是否存在,然后再读取更大的重定向文件或数据库。

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

如果存在,则将请求转发到路由处理器路由处理器将检查实际文件并将用户重定向到相应的 URL。这避免了将大型重定向文件导入到中间件中,从而减慢每个传入的请求的速度。

middleware.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()
}

然后,在路由处理器中

app/api/redirects/route.ts
import { NextRequest, NextResponse } from 'next/server'
import redirects from '@/app/redirects/redirects.json'
 
type RedirectEntry = {
  destination: string
  permanent: boolean
}
 
export function GET(request: NextRequest) {
  const pathname = request.nextUrl.searchParams.get('pathname')
  if (!pathname) {
    return new Response('Bad Request', { status: 400 })
  }
 
  // 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 new Response('No redirect', { status: 400 })
  }
 
  // Return the redirect entry
  return NextResponse.json(redirect)
}

须知

  • 要生成 Bloom 过滤器,你可以使用像 bloom-filters 这样的库。
  • 你应该验证发送到你的路由处理器的请求,以防止恶意请求。