Created
August 16, 2023 04:06
-
-
Save SaundersB/20057ac380b7084d24972180f3b018ad to your computer and use it in GitHub Desktop.
NextJS middleware.page.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextRequest, NextResponse } from 'next/server'; | |
export function middleware(request: NextRequest): Response | NextResponse { | |
const host = request.headers.get('host'); | |
if (!host) { | |
// Handle the situation where the host header is not present. | |
console.error('Host header not found.'); | |
return NextResponse.next(); | |
} | |
if (host.startsWith('www.')) { | |
console.log(`Received request with host: ${host}`); | |
const nonWwwHost = host.substring(4); // strip 'www.' | |
console.log(`Redirecting ${host} to ${nonWwwHost}`); | |
return new Response(null, { | |
status: 301, | |
headers: { | |
Location: `https://${nonWwwHost}${request.nextUrl.pathname}`, | |
}, | |
}); | |
} | |
return NextResponse.next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment