Skip to main content

redirect

redirect 函数允许你将用户重定向到另一个 URL。redirect 可用于 服务器组件路由处理程序服务器操作

¥The redirect function allows you to redirect the user to another URL. redirect can be used in Server Components, Route Handlers, and Server Actions.

当在 流上下文 中使用时,这将插入一个元标记以在客户端发出重定向。当在服务器操作中使用时,它将向调用者提供 303 HTTP 重定向响应。否则,它将向调用者提供 307 HTTP 重定向响应。

¥When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller.

如果资源不存在,你可以使用 notFound 功能

¥If a resource doesn't exist, you can use the notFound function instead.

很高兴知道:

¥Good to know:

  • 在服务器操作和路由处理程序中,redirect 应在 try/catch 块之后调用。

    ¥In Server Actions and Route Handlers, redirect should be called after the try/catch block.

  • 如果你希望返回 308(永久)HTTP 重定向而不是 307(临时),则可以使用 permanentRedirect 功能

    ¥If you prefer to return a 308 (Permanent) HTTP redirect instead of 307 (Temporary), you can use the permanentRedirect function instead.

参数

¥Parameters

redirect 函数接受两个参数:

¥The redirect function accepts two arguments:

redirect(path, type)
范围类型描述
pathstring要重定向到的 URL。可以是相对路径或绝对路径。
type'replace'(默认)或 'push'(服务器操作中的默认值)要执行的重定向类型。

默认情况下,redirect 将在其他任何地方的 服务器操作replace(替换浏览器历史记录堆栈中的当前 URL)中使用 push(向浏览器历史记录堆栈添加新条目)。你可以通过指定 type 参数来覆盖此行为。

¥By default, redirect will use push (adding a new entry to the browser history stack) in Server Actions and replace (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the type parameter.

在服务器组件中使用时,type 参数无效。

¥The type parameter has no effect when used in Server Components.

返回

¥Returns

redirect 不返回值。

¥redirect does not return a value.

示例

¥Example

服务器组件

¥Server Component

调用 redirect() 函数会引发 NEXT_REDIRECT 错误并终止引发该错误的路由段的渲染。

¥Invoking the redirect() function throws a NEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown.

import { redirect } from 'next/navigation'

async function fetchTeam(id) {
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}

export default async function Profile({ params }) {
const team = await fetchTeam(params.id)
if (!team) {
redirect('/login')
}

// ...
}

很高兴知道:redirect 不要求你使用 return redirect(),因为它使用 TypeScript never 类型。

¥Good to know: redirect does not require you to use return redirect() as it uses the TypeScript never type.

客户端组件

¥Client Component

redirect 可以通过服务器操作在客户端组件中使用。如果需要使用事件处理程序来重定向用户,可以使用 useRouter 钩子。

¥redirect can be used in a Client Component through a Server Action. If you need to use an event handler to redirect the user, you can use the useRouter hook.

'use client'

import { navigate } from './actions'

export function ClientRedirect() {
return (
<form action={navigate}>
<input type="text" name="id" />
<button>Submit</button>
</form>
)
}
'use client'

import { navigate } from './actions'

export function ClientRedirect() {
return (
<form action={navigate}>
<input type="text" name="id" />
<button>Submit</button>
</form>
)
}
'use server'

import { redirect } from 'next/navigation'

export async function navigate(data: FormData) {
redirect(`/posts/${data.get('id')}`)
}
'use server'

import { redirect } from 'next/navigation'

export async function navigate(data) {
redirect(`/posts/${data.get('id')}`)
}

常见问题

¥FAQ

为什么 redirect 用 307 和 308?

¥Why does redirect use 307 and 308?

使用 redirect() 时,你可能会注意到,使用的状态代码是 307(用于临时重定向)和 308(用于永久重定向)。虽然传统上 302 用于临时重定向,301 用于永久重定向,但许多浏览器更改了重定向的请求方法,在使用 302 时从 POST 请求更改为 GET 请求,无论来源请求方法如何。

¥When using redirect() you may notice that the status codes used are 307 for a temporary redirect, and 308 for a permanent redirect. While traditionally a 302 was used for a temporary redirect, and a 301 for a permanent redirect, many browsers changed the request method of the redirect, from a POST to GET request when using a 302, regardless of the origins request method.

以下面从 /users/people 的重定向为例,如果你向 /users 发出 POST 请求创建新用户,并且符合 302 临时重定向,则请求方法将从 POST 更改为 GET 请求。这是没有意义的,因为要创建新用户,你应该向 /people 发出 POST 请求,而不是 GET 请求。

¥Taking the following example of a redirect from /users to /people, if you make a POST request to /users to create a new user, and are conforming to a 302 temporary redirect, the request method will be changed from a POST to a GET request. This doesn't make sense, as to create a new user, you should be making a POST request to /people, and not a GET request.

307 状态码的引入意味着请求方法被保留为 POST

¥The introduction of the 307 status code means that the request method is preserved as POST.

  • 302 - 临时重定向,会将请求方法从 POST 更改为 GET

    ¥302 - Temporary redirect, will change the request method from POST to GET

  • 307 - 临时重定向,将保留请求方法为 POST

    ¥307 - Temporary redirect, will preserve the request method as POST

redirect() 方法默认使用 307,而不是 302 临时重定向,这意味着你的请求将始终保留为 POST 请求。

¥The redirect() method uses a 307 by default, instead of a 302 temporary redirect, meaning your requests will always be preserved as POST requests.

了解更多 关于 HTTP 重定向。

¥Learn more about HTTP Redirects.

版本历史

¥Version History

版本变化
v13.0.0redirect 推出。