'Next.js rewrite with x headers

I have a web app where users can build their own profiles with their usernames like below.

ourplatform.com/john
ourplatform.com/john/about
ourplatform.com/john/contact

ourplatform.com/jane
ourplatform.com/jane/about
ourplatform.com/jane/contact

They can also connect their domains so they have to be using like this.

john.com
john.com/about
john.com/contact

jane.com
jane.com/about
jane.com/contact

This is my next.config.js.

module.exports = {
  async rewrites () {
    return [
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-username',
            value: '(?<username>.*)'
          }
        ],
        destination: '/:username/:path*'
      }
    ]
  }
}

And this is the Nginx configuration.

server {
  listen 80;
  server_name john.com;

  add_header x-username "john";
  proxy_set_header x-username "john";

  location /_next {
    proxy_pass http://127.0.0.1:1323;
  }

  location = / {
    proxy_pass http://127.0.0.1:1323/john;
  }

  location / {
    proxy_pass http://127.0.0.1:1323/john$request_uri;
  }
}

But I'm getting 404 issue on the domains. What's wrong with the current setup?



Solution 1:[1]

host matching might be an alternative approach as explained here

module.exports = {
  async rewrites() {
    return [
      {
        source: '/:path*',
        has: [{ type: 'host', value: 'john.com' }],
        destination: '/john/:path*',
      },
      {
        source: '/:path*',
        has: [{ type: 'host', value: 'jane.com' }],
        destination: '/jane/:path*',
      },
    ]
  },
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jack