Next.js Discord

Discord Forum

Redirect to non-www domain middleware

Unanswered
American posted this in #help-forum
Open in Discord
AmericanOP
Hey!

I wanted to redirect from www.example.com to example.com in my middleware, but I just get stuck in endless loop. Is there a way to do it?

This is what I tried:

export async function middleware(request: NextRequest) {
  const hostnameHeader = request.headers.get("host")!;
  if (hostnameHeader.startsWith("www.")) {
    const url = request.nextUrl.clone();
    url.hostname = hostnameHeader.replace("www.", "");
    return NextResponse.redirect(url, 308);
  }

5 Replies

American black bear
Might be because you are checking headers, and the headers might not have changed? Not totally sure. try using request.nextUrl.hostname for your check instead of headers maybe
export async function middleware(request: NextRequest) {
  if (request.nextUrl.hostname.startsWith("www.")) {
    const url = request.nextUrl.clone();
    url.hostname = url.hostname.replace("www.", "");
    return NextResponse.redirect(url, 308);
  }
AmericanOP
request.nextUrl.hostname is always localhost, never www.localhost when I browse to it 🤔
American black bear
on production ? o_O
AmericanOP
No, I'm testing it locally