コンテンツにスキップ

redirects

リダイレクトにより、着信リクエストパスを別の宛先パスにリダイレクトできます。

リダイレクトを使用するには、next.config.jsredirects キーを使用できます。

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

redirects は、sourcedestination、および permanent プロパティを持つオブジェクトの配列を返すことを期待する非同期関数です。

  • sourceは、着信リクエストパスのパターンです。
  • destination は、ルーティングしたいパスです。
  • permanent true または false - true の場合は 308 ステータスコードが使用され、クライアント/検索エンジンにリダイレクトを永続的にキャッシュするように指示します。false の場合は 307 ステータスコードが使用され、一時的でありキャッシュされません。

Next.js が 307 および 308 を使用する理由 従来、一時的なリダイレクトには 302、永続的なリダイレクトには 301 が使用されていましたが、多くのブラウザは元のメソッドに関係なく、リダイレクトの要求メソッドを GET に変更していました。たとえば、ブラウザが POST /v1/users にリクエストを送信し、ステータスコード 302 と場所 /v2/users が返された場合、後続のリクエストは期待される POST /v2/users ではなく GET /v2/users になる可能性があります。Next.js は、307 一時リダイレクトと 308 永続リダイレクトのステータスコードを使用して、使用された要求メソッドを明示的に保持します。

  • basePath: false または undefined - false の場合、basePath は一致時に含まれません。外部リダイレクトのみに使用できます。
  • locale: falseまたはundefined- matching時にlocaleを含めるべきかどうか。
  • hasは、typekeyvalueプロパティを持つhasオブジェクトの配列です。
  • missingは、typekeyvalueプロパティを持つmissingオブジェクトの配列です。

リダイレクトは、ファイルシステム (ページと /public ファイルを含む) よりも前にチェックされます。

Pages Router を使用する場合、リダイレクトは、Proxy が存在し、パスと一致しない限り、クライアントサイドルーティング (Linkrouter.push) には適用されません。

リダイレクトが適用されると、要求で提供されたクエリ値はリダイレクトの宛先に渡されます。たとえば、次のリダイレクト構成を参照してください。

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

知っておくと良いこと: パスパラメータの source および destination パスで、コロン : の前にスラッシュ / を含めることを忘れないでください。そうしないと、パスはリテラル文字列として扱われ、無限リダイレクトの原因となるリスクがあります。

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

ヘッダー、Cookie、またはクエリ値が 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 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 サポート を利用する場合、リダイレクトに basePath: false を追加しない限り、各 source および destination には basePath が自動的にプレフィックスされます。

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 サポートを利用してリダイレクトする場合、設定された locales を処理するために、各 source および destination に自動的にプレフィックスが付けられます。リダイレクトに locale: false を追加しない限り、locale: false を使用すると、正しく一致するために source および destination にロケールをプレフィックスする必要があります。

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 クライアントが正しくリダイレクトできるようにカスタムステータスコードを割り当てる必要がある場合があります。この場合、permanent プロパティの代わりに statusCode プロパティを使用できますが、両方を同時に使用することはできません。IE11 との互換性を確保するために、308 ステータスコードの場合、Refresh ヘッダーが自動的に追加されます。

その他のリダイレクト

  • API Routes と Route Handlers 内で、着信リクエストに基づいてリダイレクトできます。
  • getStaticProps および getServerSideProps 内で、リクエスト時に特定のページをリダイレクトできます。

バージョン履歴

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