Skip to content

Instantly share code, notes, and snippets.

@SaundersB
Created August 16, 2023 04:06
Show Gist options
  • Save SaundersB/20057ac380b7084d24972180f3b018ad to your computer and use it in GitHub Desktop.
Save SaundersB/20057ac380b7084d24972180f3b018ad to your computer and use it in GitHub Desktop.
NextJS middleware.page.ts
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