🛬
Next.jsでサブドメインに特定のパスを割り当てる
やりたいこと
複数のプロジェクトを作ることなく、サブドメインは異なるページを割り当てたいときってありますよね!
たとえば、通常は/を返し、
https://example.com → /
特定のサブドメインからのアクセスでは
https://dashboard.example.com → /dashboard
という感じです
sourceにURLは書けない
こういうときにはNext.jsのRewritesという機能を使うことで解決できます。
参考: https://nextjs.org/docs/api-reference/next.config.js/rewrites
module.exports = {
async rewrites() {
return {
beforeFiles: [
{
source: 'https://dashboard.example.com:path*',
destination: '/dashboard:path*',
},
],
};
},
}
つまり、sourceからアクセスがあったらdestinationの値を返してもらうのです。
うまくいかない
ところが、これでデプロイすると、
Error: Invalid redirect found
と怒られます。
sourceに設定できる値はパスのみであり、URLを直接貼り付けることは許されいていないのです。
どうする
先述の通り、sourceにはパスのみしか設定できません。
なので、「ホスト名がdashboard.example.comであった場合」 という条件を使うことにしましょう。
このようなときは、hasを使うと追加で条件を設定できます。
module.exports = {
async rewrites() {
return {
beforeFiles: [
{
source: '/:path*',
has: [
{
type: 'host',
value: 'dashboard.example.com',
},
],
destination: '/dashboard:path*',
},
],
};
},
async redirects() {
return [
{
source: '/dashboard:path*',
destination: 'https://dashboard.example.com/:path*',
permanent: false,
basePath: false,
},
];
},
};
おわり
今回はhostを使用しましたが、他にもheader、cookieなどが設定できます。
このように、rewritesの機能を利用することで、URLなどに基づき、返すべページのルールを指定することができました。
Discussion