コンテンツにスキップ

rewrites

リライトにより、着信リクエストパスを別の宛先パスにマッピングできます。

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

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

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

リライトはクライアントサイドルーティングに適用されます。上記の例では、<Link href="/about">にナビゲートすると、URLは/aboutのまま、/からコンテンツが提供されます。

rewritesは非同期関数であり、`source`と`destination`プロパティを持つオブジェクトを含む配列、または配列のオブジェクトを返すことが期待されます(以下を参照)。

  • source: String - 着信リクエストパスパターンです。
  • destination: String - ルートしたいパスです。
  • basePath: falseまたはundefined- falseの場合、matching時にbasePathは含まれません。外部リライトにのみ使用できます。
  • locale: falseまたはundefined- matching時にlocaleを含めるべきかどうか。
  • 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. proxy
  4. beforeFilesリライトがチェック/適用されます
  5. public ディレクトリからの静的ファイル、_next/static ファイル、および非動的ページがチェック/提供されます
  6. afterFilesリライトがチェック/適用されます。これらのリライトのいずれかが一致した場合、一致ごとに動的ルート/静的ファイルがチェックされます。
  7. fallbackリライトがチェック/適用されます。これらは404ページをレンダリングする前、およびすべての動的ルート/静的アセットがチェックされた後に適用されます。getStaticPathsfallback: true/'blocking'を使用している場合、next.config.jsで定義されたフォールバックrewritesは実行されません。

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
      },
    ]
  },
}

パラメータが宛先に既に1つ使用されている場合、パラメータはいずれも自動的にクエリに渡されません。

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
      },
    ]
  },
}

宛先に既に1つ使用されている場合でも、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フィールドと一致しない場合にのみリライトを一致させるには、hasフィールドまたはmissingフィールドを使用できます。リライトが適用されるためには、sourceとすべてのhas項目が一致し、すべてのmissing項目が一致しない必要があります。

hasおよびmissing項目は、次のフィールドを持つことができます。

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

リライトにより、外部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パラメータにも含める必要があります。

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ルートをチェックした後、既存の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をリライトに追加しない限り、各sourcedestinationには自動的にbasePathがプレフィックスとして追加されます。

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,
      },
    ]
  },
}

バージョン履歴

バージョン変更履歴
v13.3.0missingが追加されました。
v10.2.0hasが追加されました。
v9.5.0ヘッダーが追加されました。