在 Next.js 中处理重定向有几种方法。本页面将介绍每种可用选项、用例以及如何管理大量重定向。
| API | 用途 | 位置 | 状态码 |
|---|---|---|---|
redirect | 在数据变更或事件后重定向用户 | 服务器组件、服务器 Actions、路由处理器 | 307 (Temporary) 或 303 (Server Action) |
permanentRedirect | 在数据变更或事件后重定向用户 | 服务器组件、服务器 Actions、路由处理器 | 308 (Permanent) |
useRouter | 执行客户端导航 | 客户端组件中的事件处理器 | N/A |
redirects in next.config.js | 根据路径重定向传入请求 | next.config.js 文件 | 307 (Temporary) 或 308 (Permanent) |
NextResponse.redirect | 根据条件重定向传入请求 | 代理 | Any |
| API | 用途 | 位置 | 状态码 |
|---|---|---|---|
useRouter | 执行客户端导航 | Components | N/A |
redirects in next.config.js | 根据路径重定向传入请求 | next.config.js file | 307 (Temporary) 或 308 (Permanent) |
NextResponse.redirect | 根据条件重定向传入请求 | Proxy | Any |
redirect functionredirect 函数允许您将用户重定向到另一个 URL。您可以在服务器组件、路由处理器和服务器 Actions中调用 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
}'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
}须知:
redirect默认返回 307(临时重定向)状态码。当在服务器 Action 中使用时,它返回 303(参见其他),这通常用于在 POST 请求后重定向到成功页面。redirect会抛出一个错误,因此在使用try/catch语句时,应在try块的外部调用它。redirect可以在客户端组件的渲染过程中调用,但不能在事件处理器中调用。您可以改用useRouter钩子。redirect也接受绝对 URL,可用于重定向到外部链接。- 如果您想在渲染过程之前进行重定向,请使用
next.config.js或 代理。
有关更多信息,请参阅 redirect API 参考。
permanentRedirect functionpermanentRedirect 函数允许您永久地将用户重定向到另一个 URL。您可以在服务器组件、路由处理器和服务器 Actions中调用 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
}'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') // 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 钩子中的 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>
)
}'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}如果您需要在组件内部进行重定向,可以使用 useRouter 钩子中的 push 方法。例如:
import { useRouter } from 'next/router'
export default function Page() {
const router = useRouter()
return (
<button type="button" onClick={() => router.push('/dashboard')}>
Dashboard
</button>
)
}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 参考。
有关更多信息,请参阅 useRouter API 参考。
redirects in next.config.jsnext.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 nextConfigmodule.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 in Proxy代理允许您在请求完成之前运行代码。然后,根据传入请求,使用 NextResponse.redirect 重定向到不同的 URL。如果您希望根据条件(例如身份验证、会话管理等)重定向用户,或者有大量重定向,这会很有用。
例如,如果用户未经验证,则将其重定向到 /login 页面:
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*',
}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*',
}须知:
- 代理在
next.config.js中的redirects之后,以及渲染之前运行。
有关更多信息,请参阅代理文档。
要管理大量重定向(1000+),您可以考虑使用代理创建自定义解决方案。这允许您以编程方式处理重定向,而无需重新部署应用程序。
为此,您需要考虑以下几点:
Next.js 示例:请参阅我们的带布隆过滤器的代理示例,了解以下建议的实现。
重定向映射是您可以存储在数据库(通常是键值存储)或 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 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()
}import { NextResponse } from 'next/server'
import { get } from '@vercel/edge-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()
}为每个传入请求读取大量数据集可能既缓慢又耗费资源。您可以通过两种方式优化数据查找性能:
考虑到之前的示例,您可以将生成的布隆过滤器文件导入到代理中,然后检查传入请求的路径名是否存在于布隆过滤器中。
如果存在,则将请求转发到
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()
}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()
}然后,在路由处理器中:
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)
}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)
}然后,在 API 路由中:
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)
}import redirects from '@/app/redirects/redirects.json'
export default function handler(req, res) {
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[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-filters这样的库。- 您应该验证对路由处理器发出的请求,以防止恶意请求。