サイトが8言語に対応しているが、利用規約やプライバシーポリシーは英語と日本語の2か国語しか用意していない
そのため、他言語で利用規約ページに遷移した場合には英語の利用規約ページにリダイレクトさせたい
Next.jsでリダイレクトする方法を調べた
next.config.js
module.exports = { async redirects() { return [ { source: '/about', destination: '/', permanent: true, }, ] }, }
基本の形はnext.config.js
に上記のように書けば良いだけ
permanent
は恒久的にリダイレクトさせるかどうかの設定
あとはリダイレクト元のsource
にいろいろな設定方法がある
Path Matching
/old-blog/xxxxxx
を/news/xxxxxx
にしたいときの設定
source: '/old-blog/:slug', destination: '/news/:slug',
これはネストはしない
Wildcard Path Matching
/old-blog/a/b/c/d/xxxxxx
などのようにネストしたい場合
source: '/old-blog/:slug*', destination: '/news/:slug*',
Regex Path Matching
/old-blog/123
はリダイレクトさせたいけど、 /old-blog/abc
はリダイレクトさせたくない場合
source: '/old-blog/:post(\\d{1,})', destination: '/news/:post',
Redirects with basePath support
basePath
を定義しておくことで、source
とdestination
に毎回記載する必要がなくなる
※basePathプロパティでon/off可能
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: '/another', basePath: false, permanent: false, }, ] },
Redirects with i18n support
国際化対応したルーティングをさせている場合は特定のロケールだけということが可能
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, }, ] }, }
まとめ
今回やりたかったことは正規表現をつかって次のようにするのがよさそう
{ source: '/(en|ko|zh-tw|ms|id|vi|th)/terms', destination: '/terms', permanent: true, },