9

I have a nextjs project with a :client param which represents a client, like this:

domain.com/:client

And I have multiple clients... so I need to do this rewrite:

:client.domain.com -> domain.com/:client

For example for clients:

  • google.domain.com -> domain.com/google
  • netflix.domain.com -> domain.com/netflix

...

Inside the same project.

Any way to do that?

Diego Ulloa
  • 500
  • 8
  • 19

2 Answers2

1

You can use the redirects option in the vercel.json, as Maxime mentioned.

However, it requires 1 extra key.

For example, if your app is available at company.com:

{
  ...
  redirects: [
    {
      "source": "/",
      "has": [
        {
          "type": "host",
          "value": "app.company.com"
        }
      ],
      "destination": "/app"
    }
  ]
}

More info:

ndom91
  • 719
  • 1
  • 9
  • 19
0

Create a config in your project root with next.config.js

If this file exists add the following snippet to it, Mind you, we used example.com in place of domain .com as Body cannot contain "http://domain. com" in stackoverflow

// next.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: "/:path*",
        has: [
          {
            type: "host",
            value: "client.example.com",
          },
        ],
        destination: "http://example.com/client/:path*",
        permanent: false,
      },
    ];
  },
};

To confirm it's also working in development, try with localhost

module.exports = {
  reactStrictMode: true,

  // async rewrites() {
  async redirects() {
    return [
      {
        source: "/:path*",
        has: [
          {
            type: "host",
            value: "client.localhost",
          },
        ],
        destination: "http://localhost:3000/client/:path*",
        permanent: false,
      },
    ];
  },
};

Dynamic Redirect

To make it dynamic, we'll create an array of subdomains

const subdomains = ["google", "netflix"];

module.exports = {
  async redirects() {
    return [
      ...subdomains.map((subdomain) => ({
        source: "/:path*",
        has: [
          {
            type: "host",
            value: `${subdomain}.example.com`,
          },
        ],
        destination: `https://example.com/${subdomain}/:path*`,
        permanent: false,
      })),
    ];
  },
}

You can read more from the official next.js doc redirects or rewrite

Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67