跳到主要內容

rewrites

Rewrites 允許您將傳入的請求路徑映射到不同的目標路徑。

Rewrites 充當 URL 代理並遮蔽目標路徑,使其看起來使用者未變更網站上的位置。 相反地,redirects 會重新導向至新頁面並顯示 URL 變更。

若要使用 rewrites,您可以在 next.config.js 中使用 rewrites

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

Rewrites 會套用至用戶端路由,<Link href="/about"> 將在上述範例中套用 rewrite。

rewrites 是一個非同步函式,預期會傳回陣列或陣列物件 (請參閱下方),其中包含具有 sourcedestination 屬性的物件

  • sourceString - 是傳入的請求路徑模式。
  • destinationString 是您要路由前往的路徑。
  • basePathfalseundefined - 若為 false,則比對時不會包含 basePath,僅適用於外部 rewrites。
  • localefalseundefined - 是否不應在比對時包含 locale。
  • hashas 物件 的陣列,具有 typekeyvalue 屬性。
  • missingmissing 物件 的陣列,具有 typekeyvalue 屬性。

rewrites 函式傳回陣列時,會在檢查檔案系統 (頁面和 /public 檔案) 之後和動態路由之前套用 rewrites。 當 rewrites 函式傳回具有特定形狀的陣列物件時,可以變更此行為並更精細地控制,如 Next.js v10.1 版所示

next.config.js
module.exports = {
  async rewrites() {
    return {
      beforeFiles: [
        // These rewrites are checked after headers/redirects
        // and before all files including _next/public files which
        // allows overriding page files
        {
          source: '/some-page',
          destination: '/somewhere-else',
          has: [{ type: 'query', key: 'overrideMe' }],
        },
      ],
      afterFiles: [
        // These rewrites are checked after pages/public files
        // are checked but before dynamic routes
        {
          source: '/non-existent',
          destination: '/somewhere-else',
        },
      ],
      fallback: [
        // These rewrites are checked after both pages/public files
        // and dynamic routes are checked
        {
          source: '/:path*',
          destination: `https://my-old-site.com/:path*`,
        },
      ],
    }
  },
}

小知識beforeFiles 中的 rewrites 不會在比對來源後立即檢查檔案系統/動態路由,它們會繼續直到檢查完所有 beforeFiles

Next.js 路由檢查的順序為

  1. headers 已檢查/套用
  2. redirects 已檢查/套用
  3. beforeFiles rewrites 已檢查/套用
  4. 來自 public 目錄_next/static 檔案和非動態頁面的靜態檔案已檢查/提供
  5. afterFiles rewrites 已檢查/套用,如果比對到其中一個 rewrites,我們會在每次比對後檢查動態路由/靜態檔案
  6. fallback rewrites 已檢查/套用,這些會在渲染 404 頁面之前以及在檢查完動態路由/所有靜態資源之後套用。 如果您在 getStaticPaths 中使用 fallback: true/'blocking',則在您的 next.config.js 中定義的 fallback rewrites不會執行。

Rewrite 參數

在 rewrite 中使用參數時,如果 destination 中未使用任何參數,則參數預設會以查詢字串形式傳遞。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-about/:path*',
        destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query
      },
    ]
  },
}

如果在 destination 中使用參數,則任何參數都不會自動以查詢字串形式傳遞。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/docs/:path*',
        destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
      },
    ]
  },
}

如果 destination 中已使用一個參數,您仍然可以手動在查詢字串中傳遞參數,方法是在 destination 中指定查詢字串。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/:first/:second',
        destination: '/:first?second=:second',
        // Since the :first parameter is used in the destination the :second parameter
        // will not automatically be added in the query although we can manually add it
        // as shown above
      },
    ]
  },
}

小知識:來自 自動靜態最佳化預先渲染 的靜態頁面,其來自 rewrites 的參數會在 hydration 後於用戶端上剖析,並在查詢字串中提供。

路徑匹配

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

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

萬用字元路徑匹配

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

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

正則表達式路徑匹配

若要比對正則表達式路徑,您可以將正則表達式包裝在參數後的括號中,例如 /blog/:slug(\\d{1,}) 將比對 /blog/123 但不比對 /blog/abc

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-blog/:post(\\d{1,})',
        destination: '/blog/:post', // Matched parameters can be used in the destination
      },
    ]
  },
}

下列字元 (){}[]|\^.:*+-?$ 用於正則表達式路徑匹配,因此當在 source 中用作非特殊值時,必須透過在其前面新增 \\ 來逸出它們

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

若要僅在 header、cookie 或 query 值也符合 has 欄位或不符合 missing 欄位時才比對 rewrite,可以使用 has 欄位或 missing 欄位。 source 和所有 has 項目都必須比對,且所有 missing 項目都不得比對,才能套用 rewrite。

hasmissing 項目可以有下列欄位

  • typeString - 必須是 headercookiehostquery 其中之一。
  • keyString - 要比對的選定類型中的鍵。
  • valueStringundefined - 要檢查的值,如果未定義,則任何值都將比對。 可以使用類似正則表達式的字串來擷取值的特定部分,例如,如果對 first-second 使用值 first-(?<paramName>.*),則 second 將可在 destination 中使用 :paramName
next.config.js
module.exports = {
  async rewrites() {
    return [
      // if the header `x-rewrite-me` is present,
      // this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-rewrite-me',
          },
        ],
        destination: '/another-page',
      },
      // if the header `x-rewrite-me` is not present,
      // this rewrite will be applied
      {
        source: '/:path*',
        missing: [
          {
            type: 'header',
            key: 'x-rewrite-me',
          },
        ],
        destination: '/another-page',
      },
      // if the source, query, and cookie are matched,
      // this rewrite 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',
          },
        ],
        destination: '/:path*/home',
      },
      // if the header `x-authorized` is present and
      // contains a matching value, this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        destination: '/home?authorized=:authorized',
      },
      // if the host is `example.com`,
      // this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        destination: '/another-page',
      },
    ]
  },
}

重寫到外部 URL

範例

Rewrites 允許您重寫到外部 URL。 這對於增量採用 Next.js 特別有用。 以下是將主要應用程式的 /blog 路由重新導向到外部網站的範例 rewrite。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog',
        destination: 'https://example.com/blog',
      },
      {
        source: '/blog/:slug',
        destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination
      },
    ]
  },
}

如果您使用 trailingSlash: true,您也需要在 source 參數中插入尾部斜線。 如果目標伺服器也預期尾部斜線,則應將其包含在 destination 參數中。

next.config.js
module.exports = {
  trailingSlash: true,
  async rewrites() {
    return [
      {
        source: '/blog/',
        destination: 'https://example.com/blog/',
      },
      {
        source: '/blog/:path*/',
        destination: 'https://example.com/blog/:path*/',
      },
    ]
  },
}

Next.js 的增量採用

您也可以讓 Next.js 在檢查完所有 Next.js 路由後,回退到代理到現有的網站。

這樣,當您將更多頁面遷移到 Next.js 時,就不必變更 rewrites 設定

next.config.js
module.exports = {
  async rewrites() {
    return {
      fallback: [
        {
          source: '/:path*',
          destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
        },
      ],
    }
  },
}

支援 basePath 的 Rewrites

當使用帶有 rewrites 的 basePath 支援 時,每個 sourcedestination 都會自動加上 basePath 前綴,除非您將 basePath: false 新增至 rewrite

next.config.js
module.exports = {
  basePath: '/docs',
 
  async rewrites() {
    return [
      {
        source: '/with-basePath', // automatically becomes /docs/with-basePath
        destination: '/another', // automatically becomes /docs/another
      },
      {
        // does not add /docs to /without-basePath since basePath: false is set
        // Note: this can not be used for internal rewrites e.g. `destination: '/another'`
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
      },
    ]
  },
}

支援 i18n 的 Rewrites

當使用帶有 rewrites 的 i18n 支援 時,每個 sourcedestination 都會自動加上前綴,以處理已設定的 locales,除非您將 locale: false 新增至 rewrite。 如果使用 locale: false,您必須為 sourcedestination 新增 locale 前綴,才能正確比對。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async rewrites() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        destination: '/another', // automatically passes the locale on
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        destination: '/nl/another',
        locale: false,
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        destination: '/en/another',
        locale: false,
      },
      {
        // it's possible to match all locales even when locale: false is set
        source: '/:locale/api-alias/:path*',
        destination: '/api/:path*',
        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',
      },
    ]
  },
}

版本歷史

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