|
1 | 1 | import { type NextRequest, NextResponse } from "next/server"; |
2 | 2 |
|
3 | | -export const config = { |
4 | | - matcher: [ |
5 | | - /* |
6 | | - * Match all paths except for: |
7 | | - * 1. /api routes |
8 | | - * 2. /_next (Next.js internals) |
9 | | - * 3. /_static (inside /public) |
10 | | - * 4. all root files inside /public (e.g. /favicon.ico) |
11 | | - */ |
12 | | - "/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)", |
13 | | - ], |
14 | | -}; |
| 3 | +export const config = { matcher: "/((?!.*\\.).*)" }; |
15 | 4 |
|
16 | | -const ROOT_DOMAIN = process.env.NEXT_PUBLIC_ROOT_DOMAIN; |
17 | | -export default async function middleware(req: NextRequest) { |
18 | | - // Get the request hostname (e.g. demo.thirdweb.com) |
19 | | - const hostname = req.headers.get("host"); |
| 5 | +export function middleware(request: NextRequest) { |
| 6 | + const url = request.nextUrl; |
| 7 | + const hostname = request.headers.get("host") || ""; |
20 | 8 |
|
21 | | - const searchParams = req.nextUrl.searchParams.toString(); |
22 | | - const url = req.nextUrl; |
23 | | - const path = `${url.pathname}${ |
24 | | - searchParams.length > 0 ? `?${searchParams}` : "" |
25 | | - }`; |
| 9 | + // Match pattern: something.ecosystem.domain.tld |
| 10 | + const match = hostname.match(/^([^.]+)\.ecosystem\.([^.]+\.[^.]+)$/); |
26 | 11 |
|
27 | | - // keep root application at `/` |
28 | | - if (hostname === ROOT_DOMAIN || hostname === null) { |
29 | | - return NextResponse.next(); |
30 | | - } |
| 12 | + if (match) { |
| 13 | + const [_, subdomain, primaryDomain] = match; |
| 14 | + |
| 15 | + // Redirect to ecosystem.domain.tld/subdomain |
| 16 | + const newUrl = new URL(`${url.protocol}//ecosystem.${primaryDomain}`); |
| 17 | + newUrl.pathname = `/${subdomain}${url.pathname}`; |
| 18 | + newUrl.search = url.search; |
31 | 19 |
|
32 | | - // rewrite everything else to `/[ecosystem]/... dynamic route |
33 | | - const ecosystem = hostname.split(".")[0]; |
| 20 | + // 308 is permanent redirect, preserves request method |
| 21 | + return NextResponse.redirect(newUrl, 308); |
| 22 | + } |
34 | 23 |
|
35 | | - return NextResponse.rewrite(new URL(`/${ecosystem}${path}`, req.url)); |
| 24 | + return NextResponse.next(); |
36 | 25 | } |
0 commit comments