跳到主要內容
API 參考函式permanentRedirect

permanentRedirect

permanentRedirect 函式可讓您將使用者重新導向至另一個 URL。permanentRedirect 可用於伺服器元件、用戶端元件、路由處理器伺服器行為

在串流情境中使用時,這會插入一個 meta 標籤,以便在用戶端發出重新導向。在伺服器行為中使用時,它會向呼叫者提供 303 HTTP 重新導向回應。否則,它會向呼叫者提供 308 (永久) HTTP 重新導向回應。

如果資源不存在,您可以改用 notFound 函式

小知識:如果您偏好傳回 307 (臨時) HTTP 重新導向而不是 308 (永久),您可以使用 redirect 函式

參數

permanentRedirect 函式接受兩個引數

permanentRedirect(path, type)
參數類型描述
pathstring要重新導向至的 URL。可以是相對或絕對路徑。
type'replace' (預設) 或 'push' (伺服器行為中的預設)要執行的重新導向類型。

依預設,permanentRedirect 將在 伺服器行為 中使用 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 team = await fetchTeam((await params).id)
  if (!team) {
    permanentRedirect('/login')
  }
 
  // ...
}

小知識permanentRedirect 不要求您使用 return permanentRedirect(),因為它使用 TypeScript never 類型。