跳到內容

重新導向

在 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 個以上),請考慮使用 中介軟體 建立自訂解決方案。請參閱大規模管理重新導向以取得更多資訊。
  • redirects 在中介軟體之前執行。

中介軟體中的 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 Filter 的中介軟體 範例,以了解以下建議的實作方式。

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 Filter) 以在讀取較大的重新導向檔案或資料庫之前,有效率地檢查重新導向是否存在。

考慮先前的範例,您可以將產生的 Bloom Filter 檔案匯入到中介軟體中,然後檢查傳入的請求路徑名稱是否存在於 Bloom Filter 中。

如果存在,則將請求轉發到 API 路由,該路由將檢查實際檔案並將使用者重新導向到適當的 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()
}

然後,在 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 Filter,您可以使用類似 bloom-filters 的函式庫。
  • 您應驗證對路由處理器的請求,以防止惡意請求。