コンテンツへスキップ

rewrites

リライトを使用すると、受信リクエストパスを別の宛先パスにマッピングできます。

リライトは URL プロキシとして機能し、宛先パスをマスクするため、ユーザーはサイト上の場所を変更していないように見えます。対照的に、リダイレクトは新しいページにリダイレクトし、URL の変更を表示します。

リライトを使用するには、next.config.jsrewrites キーを使用できます。

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

リライトはクライアント側のルーティングに適用されます。上記の例では、<Link href="/about"> にリライトが適用されます。

rewrites は、source プロパティと destination プロパティを持つオブジェクトを保持する配列または配列のオブジェクト (下記参照) のいずれかを返すことを期待する非同期関数です。

  • source: String - 受信リクエストパスパターンです。
  • destination: String - ルート先のパスです。
  • basePath: false または undefined - false の場合、マッチング時に basePath は含まれません。外部リライトのみに使用できます。
  • locale: false または undefined - マッチング時にロケールを含めるべきでないかどうか。
  • has は、typekeyvalue プロパティを持つ has オブジェクトの配列です。
  • missing は、typekeyvalue プロパティを持つ missing オブジェクトの配列です。

rewrites 関数が配列を返す場合、リライトはファイルシステム (ページと /public ファイル) を確認した後、動的ルートの前に適用されます。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 のリライトは、ソースのマッチング直後にファイルシステム/動的ルートを確認せず、すべての beforeFiles が確認されるまで続行します。

Next.js ルートがチェックされる順序は次のとおりです。

  1. headers がチェック/適用されます。
  2. redirects がチェック/適用されます。
  3. beforeFiles リライトがチェック/適用されます。
  4. public ディレクトリ_next/static ファイル、および非動的ページからの静的ファイルがチェック/提供されます。
  5. afterFiles リライトがチェック/適用されます。これらのリライトのいずれかが一致した場合、一致するたびに動的ルート/静的ファイルを確認します。
  6. fallback リライトがチェック/適用されます。これらは 404 ページをレンダリングする前、および動的ルート/すべての静的アセットがチェックされた後に適用されます。getStaticPathsfallback: true/'blocking' を使用する場合、next.config.js で定義されたフォールバック rewrites は実行されません。

リライトパラメーター

リライトでパラメーターを使用する場合、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
      },
    ]
  },
}

知っておくと良いこと: 自動静的最適化またはプリレンダリングの静的ページからのリライトのパラメーターは、ハイドレーション後にクライアントで解析され、クエリで提供されます。

パスのマッチング

パスのマッチングが許可されています。たとえば、/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',
      },
    ]
  },
}

ヘッダー、クッキー、またはクエリの値も一致する場合にのみリライトをマッチングするには、has フィールドを使用するか、missing フィールドを使用することができます。リライトが適用されるには、source とすべての has 項目が一致し、すべての missing 項目が一致しない必要があります。

has および missing 項目には、次のフィールドを設定できます。

  • type: String - header, cookie, host, または query のいずれかである必要があります。
  • key: String - 照合する選択されたタイプのキー。
  • value: String または undefined - チェックする値。undefined の場合は、任意の値が一致します。値の特定の部分をキャプチャするために、正規表現のような文字列を使用できます。たとえば、値 first-(?<paramName>.*)first-second に使用されている場合、second:paramName を使用して destination で使用可能になります。
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へのリライト

リライトを使用すると、外部URLにリライトできます。これは、Next.jsを段階的に導入する場合に特に役立ちます。次に、メインアプリの /blog ルートを外部サイトにリダイレクトするリライトの例を示します。

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 サーバーも末尾のスラッシュを期待している場合は、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が既存の Web サイトへのプロキシにフォールバックするようにすることもできます。

これにより、より多くのページを Next.js に移行するときに、リライト構成を変更する必要がなくなります。

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

basePathサポート付きのリライト

basePath サポートをリライトとともに利用する場合、リライトに basePath: false を追加しない限り、各 sourcedestinationbasePath が自動的にプレフィックスとして付加されます。

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サポート付きのリライト

i18n サポートをリライトとともに利用する場合、リライトに locale: false を追加しない限り、各 source および destination は、設定された locales を処理するために自動的にプレフィックスされます。locale: false を使用する場合は、正しくマッチングさせるために、source および destination にロケールをプレフィックスとして付加する必要があります。

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.0missing が追加されました。
v10.2.0has が追加されました。
v9.5.0ヘッダーが追加されました。