重新導向
在 Next.js 中有幾種處理重新導向的方法。本頁面將介紹每個可用選項、使用案例以及如何管理大量重新導向。
API | 目的 | 位置 | 狀態碼 |
---|---|---|---|
redirect | 在變更或事件後重新導向使用者 | 伺服器元件、伺服器動作、路由處理器 | 307(暫時)或 303(伺服器動作) |
permanentRedirect | 在變更或事件後重新導向使用者 | 伺服器元件、伺服器動作、路由處理器 | 308(永久) |
useRouter | 執行客戶端導航 | 客戶端元件中的事件處理器 | 不適用 |
next.config.js 中的 redirects | 根據路徑重新導向傳入請求 | next.config.js 檔案 | 307(暫時)或 308(永久) |
NextResponse.redirect | 根據條件重新導向傳入請求 | 中介軟體 | 任何 |
redirect
函式
redirect
函式允許您將使用者重新導向到另一個網址。您可以在伺服器元件、路由處理程式和伺服器動作中呼叫 redirect
。
redirect
常用於變更或事件之後。例如,建立貼文
'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
hook。redirect
也接受絕對網址,並可用於重新導向到外部連結。- 如果您想在渲染過程之前重新導向,請使用
next.config.js
或 中介軟體。
有關更多資訊,請參閱 redirect
API 參考。
permanentRedirect
函式
permanentRedirect
函式允許您**永久地**將使用者重新導向到另一個網址。您可以在伺服器元件、路由處理程式和伺服器動作中呼叫 permanentRedirect
。
permanentRedirect
常用於更改實體正規網址的變更或事件之後,例如在使用者更改使用者名稱後更新其個人檔案網址
'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
也接受絕對網址,並可用於重新導向到外部連結。- 如果您想在渲染過程之前重新導向,請使用
next.config.js
或 中介軟體。
有關更多資訊,請參閱 permanentRedirect
API 參考。
useRouter()
hook
如果您需要在客戶端元件的事件處理程式內重新導向,您可以使用 useRouter
hook 中的 push
方法。例如
'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
檔案中
module.exports = {
async redirects() {
return [
// Basic redirect
{
source: '/about',
destination: '/',
permanent: true,
},
// Wildcard path matching
{
source: '/blog/:slug',
destination: '/news/:slug',
permanent: true,
},
]
},
}
更多資訊,請參閱 redirects
API 參考。
注意事項:
中間件中的 NextResponse.redirect
中間件允許您在請求完成之前執行程式碼。然後,根據傳入的請求,使用 NextResponse.redirect
重新導向到不同的 URL。如果您想要根據條件(例如:驗證、工作階段管理等)重新導向使用者,或者有大量的重新導向,這會很有用。
例如,如果使用者未通過驗證,則將使用者重新導向到 /login
頁面
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+),您可以考慮使用中間件建立自訂解決方案。這允許您以程式設計方式處理重新導向,而無需重新部署您的應用程式。
要執行此操作,您需要考慮
- 建立和儲存重新導向映射。
- 最佳化資料查詢效能。
Next.js 範例:參考我們的 使用 Bloom 過濾器的中間件 範例,了解以下建議的實作方式。
1. 建立並儲存重新導向映射
重新導向映射是一個重新導向列表,您可以將其儲存在資料庫(通常是鍵值儲存區)或 JSON 檔案中。
請考慮以下資料結構
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
在 中間件 中,您可以從資料庫(例如 Vercel 的 邊緣設定 或 Redis)讀取資料,並根據傳入的請求重新導向使用者。
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 邊緣設定 或 Redis。
- 使用資料查找策略,例如 布隆過濾器(Bloom filter),以便在讀取較大的重新導向檔案或資料庫之前,有效率地檢查重新導向是否存在。
考慮前面的例子,您可以將產生的布隆過濾器檔案導入中介軟體,然後檢查傳入請求的路徑名稱是否存在於布隆過濾器中。
如果存在,則將請求轉發至 路由處理程式它會檢查實際檔案,並將使用者重新導向至適當的網址。這樣可以避免將大型重新導向檔案導入中介軟體,因為這會降低每個傳入請求的速度。
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()
}
然後,在路由處理程式中
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
這樣的函式庫。- 您應該驗證對路由處理程式發出的請求,以防止惡意請求。
後續步驟
這個對您有幫助嗎?