跳到内容

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

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

API目的位置状态码
redirect在修改或事件后重定向用户服务器组件、服务器操作、路由处理程序307(临时)或 303(服务器操作)
permanentRedirect在修改或事件后重定向用户服务器组件、服务器操作、路由处理程序308(永久)
useRouter执行客户端导航客户端组件中的事件处理程序不适用
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 语句时应在 try 块**外部**调用它。
  • redirect 可以在渲染过程中在客户端组件中调用,但不能在事件处理程序中调用。你可以改用useRouter 钩子
  • redirect 也接受绝对 URL,并可用于重定向到外部链接。
  • 如果你想在渲染过程之前重定向,请使用next.config.jsProxy

有关更多信息,请参阅 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.jsProxy

有关更多信息,请参阅 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+),请考虑使用 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,然后检查传入请求路径名是否存在于布隆过滤器中。

如果存在,将请求转发到路由处理程序它将检查实际文件并将用户重定向到相应的 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()
}

然后,在路由处理程序中

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-filters这样的库。
  • 你应该验证对路由处理程序发出的请求,以防止恶意请求。