permanentRedirect
permanentRedirect 函数的 API 参考。
permanentRedirect 函数允许你将用户重定向到另一个 URL。permanentRedirect 可用于服务器组件、客户端组件、路由处理器和服务器函数。
在流式渲染上下文中使用时,它会插入一个 meta 标签,以在客户端发出重定向。在服务器操作中,当 JavaScript 可用时,permanentRedirect 会执行客户端导航。对于渐进增强的表单提交,它会返回 303 HTTP 重定向响应。否则,它会返回 308(永久)HTTP 重定向响应。
如果资源不存在,你可以改用 notFound 函数。
参数
permanentRedirect 函数接受两个参数:
permanentRedirect(path, type)
| 参数 | 类型 | 描述 |
|---|---|---|
path |
string |
要重定向到的 URL。可以是相对路径或绝对路径。 |
type |
'replace'(默认)或 'push'(服务器操作中的默认值) |
要执行的重定向类型。 |
默认情况下,permanentRedirect 在服务器操作中会使用 push(向浏览器历史记录栈中添加一个新条目),在其他所有场景中则使用 replace(替换浏览器历史记录栈中的当前 URL)。你可以通过指定 type 参数来覆盖此行为。
RedirectType 对象包含 type 参数可用的选项。
import { permanentRedirect, RedirectType } from 'next/navigation'
permanentRedirect('/redirect-to', RedirectType.replace)
// or
permanentRedirect('/redirect-to', RedirectType.push)
type 参数在服务器组件中使用时不起作用。
返回值
permanentRedirect 不返回值。
行为
- 在服务器操作和路由处理器中,使用
try/catch语句时,应在try块外调用permanentRedirect,因为它会抛出错误。 - 如果你希望返回 307(临时)HTTP 重定向而非 308(永久)重定向,可以改用
redirect函数。
示例
调用 permanentRedirect() 函数会抛出 NEXT_REDIRECT 错误,并终止抛出该错误所在路由段的渲染。
app/team/[id]/page.jsjsx
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')
}
// ...
}
须知:
permanentRedirect不要求你使用return permanentRedirect(),因为它使用的是 TypeScriptnever类型。
- redirect:redirect 函数的 API 参考文档。