跳到內容

如何在 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這樣的庫。
  • 你應該驗證對路由處理程式發出的請求,以防止惡意請求。