Reputation: 195
I'm building a website with subdomains. Each subdomain is mapped to a file-based page using middleware. Below is an example of how I'm mapping subdomains to pages:
app.com
maps to /home
app.com/pricing
maps to /home/pricing
subdomain1.app.com/dashboard
maps to /_subdomains/subdomain1/dashboard
subdomain2.app.com/dashboard/home
maps to /_subdomains/subdomain2/dashboard/home
app.com
, subdomain1.app.com
and subdomain1.app.com/dashboard/
and everything else are working fine, but when I try to access subdomain1.app.com/dashboard/home
I'm getting 404 Not Found.
Here's my folder structure:
pages/
├── _subdomains/
│ └── [subdomain]/
│ ├── dashboard/
│ │ ├── home.tsx
│ │ └── index.tsx
│ └── index.tsx
├── home/
│ └── ...
└── _app.tsx
import { NextRequest, NextResponse } from 'next/server';
export const config = {
// I have a feeling this isn't matching /_subdomains/subdomain/dashboard/home
matcher: ['/', '/([^/.]*)', '/auth/([^/.]*)', '/_subdomains/:path*'],
};
export default async function middleware(req: NextRequest) {
const url = req.nextUrl;
const hostname = req.headers.get('host') || process.env.ROOT_DOMAIN;
if (!hostname) {
throw Error('Middleware -> No hostname');
}
const currentHost = hostname.replace(`.${process.env.ROOT_DOMAIN}`, '');
if (currentHost === process.env.ROOT_DOMAIN) {
url.pathname = `/home${url.pathname}`;
} else {
console.log(`/_subdomains/${currentHost}${url.pathname}`)
url.pathname = `/_subdomains/${currentHost}${url.pathname}`;
}
return NextResponse.rewrite(url);
}
I'm fairly certain it's the matcher that isn't working but I don't know why.
Matching /_subdomains/:path*
should match /_subdomains/a/b/c
according to the docs but it isn't working in this case. Or it could be another issue I'm not sure
Upvotes: 1
Views: 5975
Reputation: 195
Fixed by changing the matcher to
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /fonts (inside /public)
* 4. /examples (inside /public)
* 5. all root files inside /public (e.g. /favicon.ico)
*/
"/((?!api|_next|fonts|examples|[\\w-]+\\.\\w+).*)",
],
Thanks to this
Upvotes: 4