重定向
你可以通过多种方式处理 Next.js 中的重定向。本页将介绍每个可用选项、用例以及如何管理大量重定向。
¥There are a few ways you can handle redirects in Next.js. This page will go through each available option, use cases, and how to manage large numbers of redirects.
API | 目的 | 在哪里 | 状态码 |
---|---|---|---|
redirect | 突变或事件后重定向用户 | 服务器组件、服务器操作、路由处理程序 | 307(临时)或 303(服务器操作) |
permanentRedirect | 突变或事件后重定向用户 | 服务器组件、服务器操作、路由处理程序 | 308(永久) |
useRouter | 执行客户端导航 | 客户端组件中的事件处理程序 | 不适用 |
redirects 于 next.config.js | 根据路径重定向传入请求 | next.config.js 文件 | 307(临时)或 308(永久) |
NextResponse.redirect | 根据条件重定向传入请求 | 中间件 | 任何 |
redirect
功能
¥redirect
function
redirect
函数允许你将用户重定向到另一个 URL。你可以在 服务器组件、路由处理程序 和 服务器操作 中调用 redirect
。
¥The redirect
function allows you to redirect the user to another URL. You can call redirect
in Server Components, Route Handlers, and Server Actions.
redirect
通常在突变或事件后使用。例如,创建一个帖子:
¥redirect
is often used after a mutation or event. For example, creating a post:
'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
}
很高兴知道:
¥Good to know:
redirect
默认返回 307(临时重定向)状态代码。当在服务器操作中使用时,它会返回 303(请参阅其他),通常用于由于 POST 请求而重定向到成功页面。¥
redirect
returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request.
redirect
在内部抛出错误,因此应该在try/catch
块之外调用它。¥
redirect
internally throws an error so it should be called outside oftry/catch
blocks.
redirect
可以在渲染过程中在客户端组件中调用,但不能在事件处理程序中调用。你可以使用useRouter
钩 代替。¥
redirect
can be called in Client Components during the rendering process but not in event handlers. You can use theuseRouter
hook instead.
redirect
还接受绝对 URL,可用于重定向到外部链接。¥
redirect
also accepts absolute URLs and can be used to redirect to external links.如果你想在渲染过程之前重定向,请使用
next.config.js
或 中间件。¥If you'd like to redirect before the render process, use
next.config.js
or Middleware.
请参阅 redirect
API 参考 了解更多信息。
¥See the redirect
API reference for more information.
permanentRedirect
功能
¥permanentRedirect
function
permanentRedirect
功能允许你将用户永久重定向到另一个 URL。你可以在 服务器组件、路由处理程序 和 服务器操作 中调用 permanentRedirect
。
¥The permanentRedirect
function allows you to permanently redirect the user to another URL. You can call permanentRedirect
in Server Components, Route Handlers, and Server Actions.
permanentRedirect
通常在更改实体规范 URL 的突变或事件之后使用,例如在更改用户名后更新用户的个人资料 URL:
¥permanentRedirect
is often used after a mutation or event that changes an entity's canonical URL, such as updating a user's profile URL after they change their username:
'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
}
很高兴知道:
¥Good to know:
permanentRedirect
默认返回 308(永久重定向)状态代码。¥
permanentRedirect
returns a 308 (permanent redirect) status code by default.
permanentRedirect
还接受绝对 URL,可用于重定向到外部链接。¥
permanentRedirect
also accepts absolute URLs and can be used to redirect to external links.如果你想在渲染过程之前重定向,请使用
next.config.js
或 中间件。¥If you'd like to redirect before the render process, use
next.config.js
or Middleware.
请参阅 permanentRedirect
API 参考 了解更多信息。
¥See the permanentRedirect
API reference for more information.
useRouter()
钩
¥useRouter()
hook
如果你需要在客户端组件中的事件处理程序内部进行重定向,则可以使用 useRouter
钩子中的 push
方法。例如:
¥If you need to redirect inside an event handler in a Client Component, you can use the push
method from the useRouter
hook. For example:
'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>
)
}
很高兴知道:
¥Good to know:
请参阅 useRouter
API 参考 了解更多信息。
¥See the useRouter
API reference for more information.
redirects
于 next.config.js
¥redirects
in next.config.js
next.config.js
文件中的 redirects
选项允许你将传入请求路径重定向到不同的目标路径。当你更改页面的 URL 结构或拥有提前已知的重定向列表时,这非常有用。
¥The redirects
option in the next.config.js
file allows you to redirect an incoming request path to a different destination path. This is useful when you change the URL structure of pages or have a list of redirects that are known ahead of time.
redirects
支持 path、标头、cookie 和查询匹配,使你可以灵活地根据传入请求重定向用户。
¥redirects
supports path, header, cookie, and query matching, giving you the flexibility to redirect users based on an incoming request.
要使用 redirects
,请将选项添加到 next.config.js
文件中:
¥To use redirects
, add the option to your next.config.js
file:
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 参考 了解更多信息。
¥See the redirects
API reference for more information.
很高兴知道:
¥Good to know:
redirects
可以使用permanent
选项返回 307(临时重定向)或 308(永久重定向)状态代码。¥
redirects
can return a 307 (Temporary Redirect) or 308 (Permanent Redirect) status code with thepermanent
option.
redirects
可能对平台有限制。例如,在 Vercel 上,重定向限制为 1,024 个。要管理大量重定向 (1000+),请考虑使用 中间件 创建自定义解决方案。更多信息请参见 大规模管理重定向。¥
redirects
may have a limit on platforms. For example, on Vercel, there's a limit of 1,024 redirects. To manage a large number of redirects (1000+), consider creating a custom solution using Middleware. See managing redirects at scale for more.
redirects
在中间件之前运行。¥
redirects
runs before Middleware.
中间件中的 NextResponse.redirect
¥NextResponse.redirect
in Middleware
中间件允许你在请求完成之前运行代码。然后,根据传入请求,使用 NextResponse.redirect
重定向到不同的 URL。如果你想根据条件(例如身份验证、会话管理等)重定向用户或有 大量重定向。
¥Middleware allows you to run code before a request is completed. Then, based on the incoming request, redirect to a different URL using NextResponse.redirect
. This is useful if you want to redirect users based on a condition (e.g. authentication, session management, etc) or have a large number of redirects.
例如,如果用户未通过身份验证,则将用户重定向到 /login
页面:
¥For example, to redirect the user to a /login
page if they are not authenticated:
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*',
}
import { NextResponse } from 'next/server'
import { authenticate } from 'auth-provider'
export function middleware(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*',
}
很高兴知道:
¥Good to know:
中间件在
redirects
之后、next.config.js
中、渲染之前运行。¥Middleware runs after
redirects
innext.config.js
and before rendering.
有关详细信息,请参阅 中间件 文档。
¥See the Middleware documentation for more information.
大规模管理重定向(高级)
¥Managing redirects at scale (advanced)
要管理大量重定向(1000+),你可以考虑使用中间件创建自定义解决方案。这允许你以编程方式处理重定向,而无需重新部署应用。
¥To manage a large number of redirects (1000+), you may consider creating a custom solution using Middleware. This allows you to handle redirects programmatically without having to redeploy your application.
为此,你需要考虑:
¥To do this, you'll need to consider:
-
创建并存储重定向映射。
¥Creating and storing a redirect map.
-
优化数据查找性能。
¥Optimizing data lookup performance.
Next.js 示例:请参阅我们的 带有布隆过滤器的中间件 示例,了解以下建议的实现情况。
¥Next.js Example: See our Middleware with Bloom filter example for an implementation of the recommendations below.
1. 创建并存储重定向映射
¥ Creating and storing a redirect map
重定向映射是可以存储在数据库(通常是键值存储)或 JSON 文件中的重定向列表。
¥A redirect map is a list of redirects that you can store in a database (usually a key-value store) or JSON file.
考虑以下数据结构:
¥Consider the following data structure:
{
"/old": {
"destination": "/new",
"permanent": true
},
"/blog/post-old": {
"destination": "/blog/post-new",
"permanent": true
}
}
在 中间件 中,你可以从 Vercel 的 边缘配置 或 Redis 等数据库中读取数据,并根据传入的请求重定向用户:
¥In Middleware, you can read from a database such as Vercel's Edge Config or Redis, and redirect the user based on the incoming request:
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()
}
import { NextResponse } from 'next/server'
import { get } from '@vercel/edge-config'
export async function middleware(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. 优化数据查找性能
¥ Optimizing data lookup performance
为每个传入请求读取大型数据集可能既缓慢又昂贵。有两种方法可以优化数据查找性能:
¥Reading a large dataset for every incoming request can be slow and expensive. There are two ways you can optimize data lookup performance:
-
使用针对快速读取进行优化的数据库,例如 Vercel 边缘配置 或 Redis。
¥Use a database that is optimized for fast reads, such as Vercel Edge Config or Redis.
-
在读取较大的重定向文件或数据库之前,使用数据查找策略(例如 布隆过滤器)有效地检查重定向是否存在。
¥Use a data lookup strategy such as a Bloom filter to efficiently check if a redirect exists before reading the larger redirects file or database.
考虑到前面的示例,你可以将生成的布隆过滤器文件导入到中间件中,然后检查传入请求路径名是否存在于布隆过滤器中。
¥Considering the previous example, you can import a generated bloom filter file into Middleware, then, check if the incoming request pathname exists in the bloom filter.
如果是,则将请求转发到 路由处理程序,路由处理程序 将检查实际文件并将用户重定向到适当的 URL。这可以避免将大型重定向文件导入中间件,这会减慢每个传入请求的速度。
¥If it does, forward the request to a Route Handler which will check the actual file and redirect the user to the appropriate URL. This avoids importing a large redirects file into Middleware, which can slow down every incoming request.
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 { 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 middleware(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()
}
然后,在路由处理程序中:
¥Then, in the Route Handler:
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)
}
很高兴知道:
¥Good to know:
要生成布隆过滤器,你可以使用像
bloom-filters
这样的库。¥To generate a bloom filter, you can use a library like
bloom-filters
.你应该验证向路由处理程序发出的请求以防止恶意请求。
¥You should validate requests made to your Route Handler to prevent malicious requests.