UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Next.js】リダイレクト

サイトが8言語に対応しているが、利用規約やプライバシーポリシーは英語と日本語の2か国語しか用意していない

そのため、他言語で利用規約ページに遷移した場合には英語の利用規約ページにリダイレクトさせたい

Next.jsでリダイレクトする方法を調べた

nextjs.org

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を定義しておくことで、sourcedestinationに毎回記載する必要がなくなる
※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,
      },