如何在 Next.js 中处理重定向
了解在 Next.js 中处理重定向的不同方式。
在 Next.js 中有几种处理重定向的方式。本页将逐一介绍每个可用选项、使用场景,以及如何管理大量重定向。
| API | 用途 | 位置 | 状态码 |
|---|---|---|---|
redirect |
在变更或事件后重定向用户 | 服务器组件、服务器函数、路由处理器 | 307(临时)或 303(服务器操作) |
permanentRedirect |
在变更或事件后重定向用户 | 服务器组件、服务器函数、路由处理器 | 308(永久) |
useRouter |
执行客户端导航 | 客户端组件中的事件处理器 | N/A |
next.config.js 中的 redirects |
根据路径重定向传入请求 | next.config.js 文件 |
307(临时)或 308(永久) |
NextResponse.redirect |
根据条件重定向传入请求 | Proxy | 任意 |
redirect 函数
redirect 函数允许你将用户重定向到另一个 URL。你可以在服务器组件、路由处理器和服务器函数中调用 redirect。
redirect 常用于变更或事件之后。例如,创建一篇帖子:
TypeScript
'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
}
JavaScript
'use server'
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
export async function createPost(id) {
try {
// Call database
} catch (error) {
// Handle errors
}
revalidatePath('/posts') // Update cached posts
redirect(`/post/${id}`) // Navigate to the new post page
}
须知:
- 在服务器操作中,当 JavaScript 可用时,
redirect会执行客户端导航。若没有 JavaScript,则表单提交会使用 303(See Other)。在其他上下文中,redirect会使用 307(临时重定向)。redirect会抛出错误,因此在使用try/catch语句时,应在try块之外调用它。redirect可以在渲染过程中于客户端组件内调用,但不能在事件处理器中调用。你可以改用useRouterhook。redirect也接受绝对 URL,并可用于重定向到外部链接。- 如果你希望在渲染过程之前重定向,请使用
next.config.js或 Proxy。
有关更多信息,请参阅 redirect API 参考。
permanentRedirect 函数
permanentRedirect 函数允许你将用户永久重定向到另一个 URL。你可以在服务器组件、路由处理器和服务器函数中调用 permanentRedirect。
permanentRedirect 常用于更改实体的规范 URL 的变更或事件之后,例如在用户更改用户名后更新其个人资料 URL:
TypeScript
'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', 'max') // Update all references to the username
permanentRedirect(`/profile/${username}`) // Navigate to the new user profile
}
JavaScript
'use server'
import { permanentRedirect } from 'next/navigation'
import { revalidateTag } from 'next/cache'
export async function updateUsername(username, formData) {
try {
// Call database
} catch (error) {
// Handle errors
}
revalidateTag('username', 'max') // Update all references to the username
permanentRedirect(`/profile/${username}`) // Navigate to the new user profile
}
须知:
- 在服务器操作中,当 JavaScript 可用时,
permanentRedirect会执行客户端导航。若没有 JavaScript,则表单提交会使用 303(See Other)。在其他上下文中,permanentRedirect会使用 308(永久重定向)。permanentRedirect也接受绝对 URL,并可用于重定向到外部链接。- 如果你希望在渲染过程之前重定向,请使用
next.config.js或 Proxy。
有关更多信息,请参阅 permanentRedirect API 参考。
useRouter() hook
如果你需要在客户端组件的事件处理器中重定向,可以使用 useRouter hook 中的 push 方法。例如:
TypeScript
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}
JavaScript
'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 支持路径、header、cookie 和查询匹配,让你可以根据传入的请求灵活地重定向用户。
要使用 redirects,请将该选项添加到 next.config.js 文件中:
TypeScript
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
JavaScript
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 参考。
须知:
Proxy 中的 NextResponse.redirect
Proxy 允许你在请求完成之前运行代码。然后,根据传入的请求,使用 NextResponse.redirect 重定向到不同的 URL。如果你想根据条件(例如身份验证、会话管理等)重定向用户,或者有大量重定向,这会很有用。
例如,如果用户未通过身份验证,则将其重定向到 /login 页面:
TypeScript
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*',
}
JavaScript
import { NextResponse } from 'next/server'
import { authenticate } from 'auth-provider'
export function proxy(request) {
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 创建自定义解决方案。这样你就可以以编程方式处理重定向,而无需重新部署应用。
为此,你需要考虑:
- 创建并存储重定向映射表。
- 优化数据查找性能。
Next.js 示例:请参阅我们的 Proxy with Bloom filter 示例,了解以下建议的实现方式。
1. 创建并存储重定向映射表
重定向映射表是一份重定向列表,你可以将其存储在数据库(通常是键值存储)或 JSON 文件中。
考虑以下数据结构:
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
在 Proxy 中,你可以从 Vercel 的 Global Config 或 Redis 等数据库读取数据,并根据传入的请求重定向用户:
TypeScript
import { NextResponse, NextRequest } from 'next/server'
import { get } from '@vercel/global-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()
}
JavaScript
import { NextResponse } from 'next/server'
import { get } from '@vercel/global-config'
export async function proxy(request) {
const pathname = request.nextUrl.pathname
const redirectData = await get(pathname)
if (redirectData) {
const 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. 优化数据查找性能
为每个传入请求读取大型数据集可能既慢又昂贵。你可以通过两种方式优化数据查找性能:
- 使用针对快速读取优化的数据库
- 使用诸如 Bloom filter 之类的数据查找策略,在读取较大的重定向文件或数据库之前高效检查重定向是否存在。
基于前面的示例,你可以将生成的 bloom filter 文件导入 Proxy,然后检查传入请求的 pathname 是否存在于该 bloom filter 中。
如果存在,则将请求转发到路由处理器,由它检查实际文件并将用户重定向到适当的 URL。这样可以避免将大型重定向文件导入 Proxy,因为这会拖慢每个传入请求。
TypeScript
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()
}
JavaScript
import { NextResponse } from 'next/server'
import { ScalableBloomFilter } from 'bloom-filters'
import GeneratedBloomFilter from './redirects/bloom-filter.json'
// Initialize bloom filter from a generated JSON file
const bloomFilter = ScalableBloomFilter.fromJSON(GeneratedBloomFilter)
export async function proxy(request) {
// 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 = 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()
}
然后,在路由处理器中:
TypeScript
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)
}
JavaScript
import { NextResponse } from 'next/server'
import redirects from '@/app/redirects/redirects.json'
export function GET(request) {
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[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之类的库。- 你应该验证发送到路由处理器的请求,以防止恶意请求。
- redirect:redirect 函数的 API 参考。
- permanentRedirect:permanentRedirect 函数的 API 参考。
- proxy.js:proxy.js 文件的 API 参考。
- redirects:为你的 Next.js 应用添加重定向。