[Next.js]Next.jsでリダイレクトを設定する
Next.js9.5以降はnext.config.js
にリダイレクトの設定を記述することが可能です。
https://nextjs.org/docs/api-reference/next.config.js/redirects
通常のリダイレクト設定
以下の通りの記述をすることでリダイレクトの設定をすることが可能です。
module.exports = { async redirects() { return [ { source: '/about', // リダイレクト元 destination: '/', // リダイレクト先 permanent: true, // header指定(308) }, ] },}
パスマッチングするときの記法
例えば、/user/:id
みたいなのをリダイレクトさせたい場合は以下の記法で可能です。
module.exports = { async redirects() { return [ { source: '/user/:id', destination: '/new_user/:id', // :idがキャプチャされてリダイレクトされる permanent: true, }, ] },}
正規表現マッチング
正規表現を指定してのマッチングも行うことが可能です。
module.exports = { async redirects() { return [ { source: '/blog/:slug*', destination: '/news/:slug*', // :slug*でslug以降の任意のパスでマッチング permanent: true, }, { source: '/old-blog/:post(\\d{1,})', destination: '/blog/:post', // 正規表現も可能 permanent: false, }, ] },}