跳至內容

重新導向 (redirects)

重新導向允許您將傳入的請求路徑重新導向到不同的目標路徑。

要使用重新導向,您可以在 `next.config.js` 中使用 `redirects` 鍵。

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
    ]
  },
}

`redirects` 是一個非同步函式,它預期返回一個陣列,其中包含具有 `source`、`destination` 和 `permanent` 屬性的物件。

  • `source` 是傳入的請求路徑模式。
  • `destination` 是您要路由到的路徑。
  • `permanent` 為 `true` 或 `false` - 如果為 `true`,將使用 308 狀態碼,指示客戶端/搜尋引擎永久快取重新導向;如果為 `false`,將使用 307 狀態碼,這是暫時的且不會被快取。

Next.js 為何使用 307 和 308?傳統上,302 用於暫時重新導向,301 用於永久重新導向,但許多瀏覽器會將重新導向的請求方法更改為 GET,而不管原始方法為何。例如,如果瀏覽器發出 POST /v1/users 的請求,返回狀態碼 302 以及位置 /v2/users,則後續請求可能是 GET /v2/users,而不是預期的 POST /v2/users。Next.js 使用 307 暫時重新導向和 308 永久重新導向狀態碼來明確保留使用的請求方法。

  • basePathfalseundefined - 如果為 false,則在比對時不會包含 basePath,僅可用於外部重新導向。
  • localefalseundefined - 是否在比對時不包含語系設定。
  • has 是一個 has 物件 的陣列,具有 typekeyvalue 屬性。
  • missing 是一個 missing 物件 的陣列,具有 typekeyvalue 屬性。

重新導向會在檔案系統(包含頁面和 /public 檔案)之前檢查。

使用 Pages Router 時,重新導向不會套用至用戶端路由(Linkrouter.push),除非存在 中間件 並且符合路徑。

套用重新導向時,請求中提供的任何查詢值都會傳遞到重新導向目的地。例如,請參考下列重新導向設定

{
  source: '/old-blog/:path*',
  destination: '/blog/:path*',
  permanent: false
}

當請求 /old-blog/post-1?hello=world 時,用戶端將會被重新導向至 /blog/post-1?hello=world

路徑比對

允許路徑比對,例如 /old-blog/:slug 將會比對 /old-blog/hello-world(無巢狀路徑)

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/old-blog/:slug',
        destination: '/news/:slug', // Matched parameters can be used in the destination
        permanent: true,
      },
    ]
  },
}

萬用字元路徑比對

要比對萬用字元路徑,您可以在參數後使用 *,例如 /blog/:slug* 將會比對 /blog/a/b/c/d/hello-world

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/blog/:slug*',
        destination: '/news/:slug*', // Matched parameters can be used in the destination
        permanent: true,
      },
    ]
  },
}

正規表達式路徑比對

要比對正規表達式路徑,您可以在參數後用括號括住正規表達式,例如 /post/:slug(\\d{1,}) 將會比對 /post/123,但不會比對 /post/abc

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/post/:slug(\\d{1,})',
        destination: '/news/:slug', // Matched parameters can be used in the destination
        permanent: false,
      },
    ]
  },
}

以下字元 (){}:*+? 用於正規表達式路徑比對,因此當在 source 中使用非特殊值時,必須在其前面加上 \\ 來進行跳脫

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        destination: '/en-us/:slug',
        permanent: false,
      },
    ]
  },
}

可以使用 has 欄位和 missing 欄位來比對標頭、Cookie 或查詢參數,只有在符合 has 欄位中的條件或不符合 missing 欄位中的條件時,才會執行重新導向。必須同時符合 source 和所有 has 項目的條件,且所有 missing 項目的條件皆不符合,才會套用重新導向。

hasmissing 項目可以包含以下欄位:

  • typeString 類型 - 必須是 headercookiehostquery 其中之一。
  • keyString 類型 - 要比對的所選類型的鍵值。
  • valueString 類型或 undefined - 要檢查的值,如果未定義,則任何值都符合。可以使用類似正規表達式的字串來擷取值的特定部分,例如,如果值 first-(?<paramName>.*) 用於 first-second,則 second 將可在目的地中使用 :paramName 來使用。
next.config.js
module.exports = {
  async redirects() {
    return [
      // if the header `x-redirect-me` is present,
      // this redirect will be applied
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'header',
            key: 'x-redirect-me',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // if the header `x-dont-redirect` is present,
      // this redirect will NOT be applied
      {
        source: '/:path((?!another-page$).*)',
        missing: [
          {
            type: 'header',
            key: 'x-do-not-redirect',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // if the source, query, and cookie are matched,
      // this redirect will be applied
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // the page value will not be available in the
            // destination since value is provided and doesn't
            // use a named capture group e.g. (?<page>home)
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        permanent: false,
        destination: '/another/:path*',
      },
      // if the header `x-authorized` is present and
      // contains a matching value, this redirect will be applied
      {
        source: '/',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        permanent: false,
        destination: '/home?authorized=:authorized',
      },
      // if the host is `example.com`,
      // this redirect will be applied
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
    ]
  },
}

支援 basePath 的重新導向

當利用basePath 支援進行重新導向時,每個 sourcedestination 都會自動加上 basePath 作為前綴,除非您在重新導向中加入 basePath: false

next.config.js
module.exports = {
  basePath: '/docs',
 
  async redirects() {
    return [
      {
        source: '/with-basePath', // automatically becomes /docs/with-basePath
        destination: '/another', // automatically becomes /docs/another
        permanent: false,
      },
      {
        // does not add /docs since basePath: false is set
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
        permanent: false,
      },
    ]
  },
}

支援 i18n 的重新導向 i18n 支援進行重新導向時,每個 sourcedestination 都會自動加上前綴來處理已設定的 locales,除非您在重新導向中加入 locale: false。如果使用了 locale: false,您必須在 sourcedestination 前面加上地區設定,才能正確比對。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async redirects() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        destination: '/another', // automatically passes the locale on
        permanent: false,
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        destination: '/nl/another',
        locale: false,
        permanent: false,
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        destination: '/en/another',
        locale: false,
        permanent: false,
      },
      // it's possible to match all locales even when locale: false is set
      {
        source: '/:locale/page',
        destination: '/en/newpage',
        permanent: false,
        locale: false,
      },
      {
        // this gets converted to /(en|fr|de)/(.*) so will not match the top-level
        // `/` or `/fr` routes like /:path* would
        source: '/(.*)',
        destination: '/another',
        permanent: false,
      },
    ]
  },
}

在某些少數情況下,您可能需要為較舊的 HTTP 用戶端指定自訂狀態碼才能正確重新導向。在這些情況下,您可以使用 statusCode 屬性來取代 permanent 屬性,但不能同時使用兩者。為了確保 IE11 的相容性,系統會自動為 308 狀態碼加入 Refresh 標頭。

其他重新導向

版本歷史記錄

版本變更
v13.3.0新增 missing
v10.2.0新增 has
v9.5.0新增 redirects