70 lines
2.7 KiB
TypeScript
70 lines
2.7 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
|
|
/**
|
|
* PRODUCTION STABILIZATION MIDDLEWARE
|
|
* This middleware handles legacy asset routing for the KLZ showcase,
|
|
* ensuring assets are correctly mapped regardless of Next.js config wrapper behavior.
|
|
*/
|
|
export function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
|
|
// 2. Legacy Showcase Asset Mapping
|
|
// Handles:
|
|
// - Global assets (/wp-content/*, /wp-includes/*, /assets/*)
|
|
// - Showcase-specific resources (/case-studies/klz-cables/index.html, etc.)
|
|
|
|
// Normalize pathname to ensure we're matching correctly
|
|
const path = pathname;
|
|
|
|
// Map Pattern 2: Showcase-prefixed assets (used for relative links within the showcase)
|
|
const showcaseMatch = path.match(/^\/(?:case-studies|work|blog)\/([^\/]+)\/(.*)/);
|
|
if (showcaseMatch) {
|
|
let [, slug, remainingPath] = showcaseMatch;
|
|
|
|
// Safety: Only rewrite if it looks like a static asset (has extension)
|
|
// or belongs to known legacy folders. This prevents catching Next.js routes.
|
|
if (remainingPath.match(/\.(?:html|php|js|css|png|jpg|jpeg|svg|gif|webp|woff2?|ttf|pdf|json|xml)$/) ||
|
|
remainingPath.includes('wp-content/') ||
|
|
remainingPath.includes('wp-includes/') ||
|
|
remainingPath.includes('assets/')) {
|
|
|
|
// If the URL resolved to /case-studies/assets/..., 'assets' is captured as the slug
|
|
if (slug === 'assets') {
|
|
const nextSlash = remainingPath.indexOf('/');
|
|
if (nextSlash !== -1) {
|
|
const actualDir = remainingPath.substring(0, nextSlash);
|
|
slug = actualDir === 'klz-cables.com' ? 'klz-cables' : actualDir; // Normalize back to expected slug
|
|
remainingPath = remainingPath.substring(nextSlash + 1);
|
|
}
|
|
}
|
|
|
|
// Normalize slug: klz-cables -> klz-cables.com (literal folder name)
|
|
const directory = slug === 'klz-cables' ? 'klz-cables.com' : slug;
|
|
|
|
// If the remaining path already starts with assets/directory, don't double it
|
|
const targetPath = remainingPath.startsWith(`assets/${directory}/`)
|
|
? `/${remainingPath}`
|
|
: `/assets/${directory}/${remainingPath}`;
|
|
|
|
console.log(`[Middleware] Rewriting to: /showcase/${directory}${targetPath}`);
|
|
return NextResponse.rewrite(new URL(`/showcase/${directory}${targetPath}`, request.url));
|
|
}
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// Optimization: Only run middleware for legacy asset paths to minimize overhead
|
|
export const config = {
|
|
matcher: [
|
|
'/wp-content/:path*',
|
|
'/wp-includes/:path*',
|
|
'/assets/:path*',
|
|
'/case-studies/:path*',
|
|
'/work/:path*',
|
|
'/blog/:path*',
|
|
],
|
|
};
|