Preview: middleware.ts
Size: 1.87 KB
/var/www/nea-dev-frontend.wpress.dk/httpdocs/src/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { findRedirect } from '@/lib/redirection'
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
// ignore homepage and files
if (
pathname === '/' ||
pathname.startsWith('/_next') ||
pathname.includes('.') // static files
) {
return NextResponse.next()
}
// Normalize pathname (remove double slashes) before processing
const normalizedPathname = pathname.replace(/\/+/g, '/')
// Check for WordPress redirects
try {
const redirect = await findRedirect(normalizedPathname)
if (redirect) {
// Get the target URL (already processed by convertToFrontendUrl)
let targetUrl = redirect.targetUrl.trim()
// Check if it's a full URL (http:// or https://)
const isFullUrl = targetUrl.startsWith('http://') || targetUrl.startsWith('https://')
// Normalize double slashes only for relative paths
if (!isFullUrl && targetUrl.startsWith('/')) {
targetUrl = targetUrl.replace(/\/+/g, '/')
}
// Prevent redirect loops - don't redirect to the same path
if (!isFullUrl && (targetUrl === normalizedPathname || targetUrl === pathname)) {
return NextResponse.next()
}
// Create the redirect URL
const redirectUrl = isFullUrl
? new URL(targetUrl)
: new URL(targetUrl, request.nextUrl.origin)
return NextResponse.redirect(redirectUrl, redirect.statusCode)
}
} catch (error) {
// Continue if redirect check fails
}
// add trailing slash if missing (only if pathname is normalized)
if (!normalizedPathname.endsWith('/')) {
const url = request.nextUrl.clone()
url.pathname = `${normalizedPathname}/`
return NextResponse.redirect(url, 301)
}
return NextResponse.next()
}
Directory Contents
Dirs: 17 × Files: 1