重新導向
在 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
通常在變更或事件後使用。例如,建立貼文
'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
也接受絕對 URL,可用於重新導向到外部連結。- 如果您想在渲染過程之前重新導向,請使用
next.config.js
或 中介軟體。
有關更多資訊,請參閱 redirect
API 參考。
permanentRedirect
函式
permanentRedirect
函式允許您將使用者永久重新導向到另一個 URL。您可以在伺服器組件、路由處理器和伺服器動作中呼叫 permanentRedirect
。
permanentRedirect
通常在變更或事件後使用,這些變更或事件會變更實體的標準 URL,例如在使用者變更使用者名稱後更新使用者的個人資料 URL
'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()
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
檔案
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 參考。
要知道的好事:
Middleware 中的 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 filter 的中介軟體 範例,以取得以下建議的實作範例。
1. 建立和儲存重新導向地圖
重新導向地圖是您可以儲存在資料庫 (通常是鍵值儲存區) 或 JSON 檔案中的重新導向清單。
考慮以下資料結構
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
在中介軟體中,您可以從資料庫讀取,例如 Vercel 的 Edge Config 或 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 Edge Config 或 Redis。
- 使用資料查詢策略,例如 Bloom filter,以在讀取較大的重新導向檔案或資料庫之前,有效率地檢查重新導向是否存在。
考慮到先前的範例,您可以將產生的 bloom filter 檔案匯入中介軟體,然後檢查傳入的請求路徑名稱是否存在於 bloom filter 中。
如果存在,則將請求轉發到 路由處理器路由處理器將檢查實際檔案,並將使用者重新導向到適當的 URL。這樣可以避免將大型重新導向檔案匯入中介軟體,這可能會減慢每個傳入的請求。
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 filter,您可以使用類似
bloom-filters
的函式庫。- 您應驗證對路由處理器提出的請求,以防止惡意請求。
下一步
這篇文章對您有幫助嗎?