Skip to content

Commit

Permalink
feat: middleware에서 wildcard 서브도메인 rewrite로직
Browse files Browse the repository at this point in the history
  • Loading branch information
WooWan committed Aug 5, 2024
1 parent cf88f72 commit ad4c975
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/app/(playground)/pg/[subdomain]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page({ params }: { params: { subdomain: string } }) {
return <div>Subdomain: {params.subdomain}</div>;
}
31 changes: 31 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export const config = {
matcher: ["/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)"],
};

export function middleware(request: NextRequest) {
const url = request.nextUrl;
const hostname = request.headers
.get("host")!
.replace(".localhost:3000", `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);
const searchParams = request.nextUrl.searchParams.toString();

const path = `${url.pathname}${
searchParams.length > 0 ? `?${searchParams}` : ""
}`;

const subDomain = hostname.split(".")[0];

switch (true) {
case subDomain !== hostname:
console.log(`/pg/${subDomain}${path}`);
return NextResponse.rewrite(
new URL(`/pg/${subDomain}${path}`, request.url),
);

default:
return NextResponse.rewrite(new URL(`${path}`, request.url));
}
}

0 comments on commit ad4c975

Please sign in to comment.