Skip to content

Subdomain Pages Bypass #456

@kecoliva

Description

@kecoliva

This sample allows subdomains to be accessed from the root domain:

https://hello.vercel.pub could be accessed by going to https://vercel.pub/s/hello

Adding in

// Block access to the subdomain pages from the root domain
if (pathname.startsWith('/s/')) {
  return NextResponse.rewrite(new URL('/404', request.url))
}

would fix it.

middleware.ts

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const subdomain = extractSubdomain(request);

  if (subdomain) {
    // Block access to admin page from subdomains
    if (pathname.startsWith('/admin')) {
      return NextResponse.redirect(new URL('/', request.url));
    }

    // For the root path on a subdomain, rewrite to the subdomain page
    if (pathname === '/') {
      return NextResponse.rewrite(new URL(`/s/${subdomain}`, request.url));
    }
  }

  // Block access to the subdomain pages from the root domain
  if (pathname.startsWith('/s/')) {
    return NextResponse.rewrite(new URL('/404', request.url))
  }

  // On the root domain, allow normal access
  return NextResponse.next();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions