How to redirect pages/app folder to subdomain in next.js

Viewed 4001

I search a lot for this on the internet but I don't find any article related to it.

Like I have a folder called pages in the root of my project and below tree is files of it.

|   404.js
|   auth.js
|   index.js
|   _app.js
|   _error.js
\---app
        index.js

next.js gives default behavior when someone opens project.local:3000 it will openindex.js and project.local:3000/app it will open app/index.js but I want that when someone open app.project.local:3000 it will open app/index.js.

My Hosts file

127.0.0.1 project.local
127.0.0.1 app.project.local

In short

I want to redirect pages/app folder to app.project.local or app.example.com in next.js

3 Answers

I'm still a noobie in next.js (2nd day learning), but I was searching for subdomain support and I found three solutions on this Github issue: https://github.com/vercel/next.js/issues/5682

  1. Using zones (still no idea how it works)
  2. "Vercel will implement subdomain routing in the near future" (I don't expect to use Vercel in the near future)
  3. (my preferred, but not yet tested) An example using custom servers in Next.js: https://github.com/dcangulo/nextjs-subdomain-example For #3, see how it was implemented in the server.js file

Most updated solution

I found the solution while exploring the documentation on redirects.

In your Next.js's root folder, create a vercel.json file and then insert your redirects as object inside redirects array like so:

{
  "redirects": [
    { "source": "/blog", "destination": "https://blog.example.com" }
  ]
}

This will only work on production environment. It should work as intended.

NextJS now supports Locales: https://nextjs.org/docs/advanced-features/i18n-routing.

You can specify a locale in your config, e.g. admin and specify the URL like this:

// next.config.js
module.exports = {
  i18n: {
    // These are all the locales you want to support in
    // your application
    locales: ['en-US', 'admin', 'nl-NL'],
    // This is the default locale you want to be used when visiting
    // a non-locale prefixed path e.g. `/hello`
    defaultLocale: 'en-US',
    // This is a list of locale domains and the default locale they
    // should handle (these are only required when setting up domain routing)
    // Note: subdomains must be included in the domain value to be matched e.g. "fr.example.com".
    domains: [
      {
        domain: 'example.com',
        defaultLocale: 'en-US',
      },
      {
        domain: 'example.nl',
        defaultLocale: 'nl-NL',
      },
      {
        domain: 'admin.example.com',
        defaultLocale: 'admin',
        // an optional http field can also be used to test
        // locale domains locally with http instead of https
        http: true,
      },
    ],
  },
}
Related