コンテンツへスキップ

redirects

リダイレクトを使用すると、受信したリクエストパスを別の宛先パスにリダイレクトできます。

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

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

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

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

なぜ Next.js は 307 と 308 を使用するのですか? 従来、一時的なリダイレクトには 302 が、永続的なリダイレクトには 301 が使用されていましたが、多くのブラウザは、元のメソッドに関係なく、リダイレクトのリクエストメソッドを GET に変更しました。たとえば、ブラウザが POST /v1/users にリクエストを行い、ロケーション /v2/users でステータスコード 302 を返した場合、後続のリクエストは、予期される POST /v2/users の代わりに GET /v2/users になる可能性があります。Next.js は、使用されたリクエストメソッドを明示的に保持するために、307 一時リダイレクトと 308 永続リダイレクトステータスコードを使用します。

  • basePath: false または undefined - false の場合、マッチング時に basePath は含まれません。外部リダイレクトでのみ使用できます。
  • locale: false または undefined - マッチング時にロケールを含めるべきではないかどうか。
  • has は、typekey、および value プロパティを持つ has オブジェクトの配列です。
  • missing は、typekey、および value プロパティを持つ missing オブジェクトの配列です。

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

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

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

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

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

リダイレクトを適用する際に、ヘッダー、クッキー、またはクエリの値が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のサポートを利用する場合、リダイレクトごとにsourcedestinationは、リダイレクトにbasePath: falseを追加しない限り、自動的に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のサポートを利用する場合、リダイレクトごとにsourcedestinationは、リダイレクトにlocale: falseを追加しない限り、構成されたlocalesを処理するために自動的にプレフィックスとして付加されます。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クライアントが正しくリダイレクトするために、カスタムステータスコードを割り当てる必要がある場合があります。このような場合、permanentプロパティの代わりにstatusCodeプロパティを使用できますが、両方を同時に使用することはできません。IE11との互換性を確保するために、308ステータスコードにはRefreshヘッダーが自動的に追加されます。

その他のリダイレクト

バージョン履歴

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