跳到主要內容

redirects

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

若要使用重新導向,您可以使用 next.config.js 中的 redirects

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

redirects 是一個非同步函式,預期會傳回一個陣列,其中包含具有 sourcedestinationpermanent 屬性的物件

  • source 是傳入的請求路徑模式。
  • destination 是您想要路由到的路徑。
  • permanent truefalse - 若為 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
}

小提示:請記住在 sourcedestination 路徑的路徑參數中,在冒號 : 之前包含正斜線 /,否則路徑將被視為文字字串,並且您可能會冒著造成無限重新導向的風險。

當請求 /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,
      },
    ]
  },
}

Regex 路徑匹配

若要匹配 Regex 路徑,您可以將 Regex 包裹在參數後的括號中,例如 /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,
      },
    ]
  },
}

以下字元 (){}:*+? 用於 Regex 路徑匹配,因此當在 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,
      },
    ]
  },
}

若要僅在 Header、Cookie 或 Query 值也符合 has 欄位或不符合 missing 欄位時才匹配重新導向,可以使用 has 欄位或 missing 欄位。 source 和所有 has 項目都必須匹配,並且所有 missing 項目都不得匹配,才能應用重新導向。

hasmissing 項目可以具有以下欄位

  • typeString - 必須為 headercookiehostquery 其中之一。
  • keyString - 要比對的選定類型中的鍵。
  • valueStringundefined - 要檢查的值,如果未定義,則任何值都將匹配。 可以使用類似 Regex 的字串來擷取值的特定部分,例如,如果值 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 Header。

其他重新導向

版本歷史

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