redirects
Redirects は、着信する request path を異なる destination path に redirect することを可能にします。
next.config.jsの中でredirectsキーを使用して、 redirects を使用することができます:
module.exports = {
async redirects() {
return [
{
source: '/about',
destination: '/',
permanent: true,
},
]
},
}
redirectsは、source、destination、およびpermanentのプロパティを持つ Object を保持する配列が返されることを期待する async 関数です。
sourceis the incoming request path pattern.destinationはあなたが route したい path です。permanenttrueまたはfalse-trueの場合、Client/検索エンジンに永久に redirect を cache するよう指示する 308 の code が使用され、falseの場合、一時的でキャッシュされない 307 の code が使用されます。
なぜ Next.js は 307 と 308 を使用するのか? 従来、302 は一時的な redirect 用、301 は permanent redirect 用に使用されていましたが、多くのブラウザが redirect の request method を元の method に関わらず
GETに変更してしまいます。例えば、ブラウザがPOST /v1/usersに request し、ステータス code302と場所/v2/usersが返された場合、次の request は期待されるPOST /v2/usersではなくGET /v2/usersになる可能性があります。Next.js は、使用された request method を明確に保持するために、307 の一時的な redirect と 308 の permanent redirect のステータスコードを使用します。
basePath:falseまたはundefined- false の場合、マッチング時にbasePathは含まれず、外部の redirects にのみ使用できます。locale:falseorundefined- whether the locale should not be included when matching.hasis an array of has objects with thetype,keyandvalueproperties.missingis an array of missing objects with thetype,keyandvalueproperties.
Redirects は、ページと/publicファイルを含むファイルシステムの前にチェックされます。
Link、router.pushなどのクライアントサイドルーティングに対して Pages Router を使用する際、Middlewareが存在し、かつ、path と一致している場合を除き、redirects は適用されません。
redirect が適用されると、request で提供されたすべてのクエリ values が redirect 先に渡されます。例えば、以下の redirect 設定をご覧ください:
{
source: '/old-blog/:path*',
destination: '/blog/:path*',
permanent: false
}
/old-blog/post-1?hello=worldが Request されたとき、client は/blog/post-1?hello=worldに Redirect されます。
Path Matching
Path マッチは許可されており、例えば/old-blog/:slugは/old-blog/hello-worldとマッチします(ネストされた paths はありません):
module.exports = {
async redirects() {
return [
{
source: '/old-blog/:slug',
destination: '/news/:slug', // Matched parameters can be used in the destination
permanent: true,
},
]
},
}
Wildcard Path Matching
ワイルドカードパスに一致させたい場合、パラメーターの後に*を使用できます。例えば、/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,
},
]
},
}
Regex Path Matching
パラメーターの後に正規表現を括弧でくるむことで、正規表現 path と一致させることができます。たとえば、/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,
},
]
},
}
Header, Cookie, and Query Matching
hasフィールドと一致するか、missingフィールドと一致しない場合にのみ、redirect が一致するように、header、cookie、または query の値も一致します。sourceとすべてのhas項目が一致し、すべてのmissing項目が一致しなければ、redirect が適用されます。
has と missing アイテムには以下のフィールドがあります:
type:String-header、cookie、host、またはqueryのいずれかでなければなりません。key:String- 選択されたタイプから一致させるためのキー。value:Stringまたは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',
},
]
},
}
Redirects は basePath サポートと共に
basePathサポートを使用して redirect すると、各 source および destination は、 basePath: false を redirects に追加しない限り、自動的に 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,
},
]
},
}
Redirects が i18n をサポート
i18n サポートを redirects と組み合わせて使用する場合、各sourceとdestinationは、設定されたlocalesを処理するために自動的に接頭辞が付けられます。ただし、 redirect に対して、locale: falseを追加するとその接頭辞は付かなくなります。locale: falseを使用する場合、sourceとdestinationに locale の接頭辞を付けて、正しく一致させる必要があります。
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,
},
]
},
}
一部の稀なケースでは、古い HTTPClient が適切に redirect するためにカスタムステータス code を割り当てる必要があるかもしれません。これらのケースでは、permanentプロパティの代わりにstatusCodeプロパティを使用できますが、両方を使用することはできません。IE11 の互換性を確保するために、308 のステータス code に対してRefreshheader が自動的に追加されます。
Other Redirects
- API RoutesとRoute Handlersの内部では、着信の request に基づいて redirect することができます。
getStaticPropsとgetServerSidePropsの中で、Request 時に特定のページを redirect することができます。
Version History
| Version | Changes |
|---|---|
v13.3.0 | missing added. |
v10.2.0 | has added. |
v9.5.0 | redirectsが追加されました。 |