redirects
リダイレクトにより、着信リクエストパスを別の宛先パスにリダイレクトできます。
リダイレクトを使用するには、next.config.js の redirects キーを使用できます。
module.exports = {
  async redirects() {
    return [
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
    ]
  },
}redirects は、source、destination、および 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は、- type、- key、- valueプロパティを持つhasオブジェクトの配列です。
- missingは、- type、- key、- valueプロパティを持つmissingオブジェクトの配列です。
リダイレクトは、ファイルシステム (ページと /public ファイルを含む) よりも前にチェックされます。
Pages Router を使用する場合、リダイレクトは、Proxy が存在し、パスと一致しない限り、クライアントサイドルーティング (Link、router.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 (ネストされたパスなし) と一致します。
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に一致します。
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 とは一致しません。
module.exports = {
  async redirects() {
    return [
      {
        source: '/post/:slug(\\d{1,})',
        destination: '/news/:slug', // Matched parameters can be used in the destination
        permanent: false,
      },
    ]
  },
}特殊文字(、)、{、}、:、*、+、?は正規表現パスマッチングに使用されるため、sourceで特殊でない値として使用する場合は、前に\\を追加してエスケープする必要があります。
module.exports = {
  async redirects() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        destination: '/en-us/:slug',
        permanent: false,
      },
    ]
  },
}ヘッダー、Cookie、クエリのマッチング
ヘッダー、Cookie、またはクエリ値が has フィールドと一致する場合、または missing フィールドと一致しない場合にのみリダイレクトを一致させたい場合は、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で宛先で使用できます。
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 が自動的にプレフィックスされます。
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 にロケールをプレフィックスする必要があります。
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.0 | missingが追加されました。 | 
| v10.2.0 | hasが追加されました。 | 
| v9.5.0 | redirectsが追加されました。 | 
役に立ちましたか?