permanentRedirect

permanentRedirect 函数允许你将用户重定向到另一个 URL。该函数可用于服务端组件 (Server Components)、客户端组件 (Client Components)、路由处理器 (Route Handlers) 以及 服务端操作 (Server Actions)

在流式传输 (streaming) 上下文中使用时,该函数会插入一个 meta 标签以在客户端触发重定向。在服务端操作中使用时,会向调用方返回 303 HTTP 重定向响应。其他情况下会返回 308(永久)HTTP 重定向响应。

如果资源不存在,可以使用 notFound 函数 替代。

须知:若希望返回 307(临时)HTTP 重定向而非 308(永久),可以使用 redirect 函数

参数

permanentRedirect 函数接受两个参数:

permanentRedirect(path, type)
参数类型描述
pathstring重定向目标 URL,可以是相对路径或绝对路径。
type'replace'(默认值)或 'push'(服务端操作中默认值)指定重定向类型。

默认情况下,在服务端操作 (Server Actions) 中会使用 push(在浏览器历史记录栈中添加新条目),其他场景会使用 replace(替换浏览器历史记录栈中的当前 URL)。可通过指定 type 参数覆盖此行为。

在服务端组件中使用时,type 参数不会产生任何效果。

返回值

permanentRedirect 不返回任何值。

示例

调用 permanentRedirect() 函数会抛出 NEXT_REDIRECT 错误,并终止所在路由段的渲染。

app/team/[id]/page.js
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 { id } = await params
  const team = await fetchTeam(id)
  if (!team) {
    permanentRedirect('/login')
  }

  // ...
}

须知:由于使用了 TypeScript 的 never 类型,调用 permanentRedirect 时无需使用 return permanentRedirect()

On this page