Skip to main content

permanentRedirect

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

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

当在流上下文中使用时,这将插入一个元标记以在客户端发出重定向。当在服务器操作中使用时,它将向调用者提供 303 HTTP 重定向响应。否则,它将向调用者提供 308(永久)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 308 (Permanent) HTTP redirect response to the caller.

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

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

很高兴知道:如果你希望返回 307(临时)HTTP 重定向而不是 308(永久),则可以使用 redirect 功能

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

参数

¥Parameters

permanentRedirect 函数接受两个参数:

¥The permanentRedirect function accepts two arguments:

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

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

¥By default, permanentRedirect 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

permanentRedirect 不返回任何值。

¥permanentRedirect does not return any value.

示例

¥Example

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

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

import { permanentRedirect } 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) {
permanentRedirect('/login')
}

// ...
}

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

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