From 63f1aef752092d140c838079bfccefad0189c601 Mon Sep 17 00:00:00 2001 From: Alireza Hassani Date: Sat, 29 Aug 2026 23:23:50 +0330 Subject: [PATCH] Redirect locale using the public Host header, not NextURL.origin. A relative Location is invalid in Next.js 15 middleware; the Host header is the public site while nextUrl stays on the PM2 bind address. Co-authored-by: Cursor --- src/middleware.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index 2293ab8..2122b5d 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -16,12 +16,19 @@ export function middleware(request: NextRequest) { ); if (hasLocale || PUBLIC_FILE.test(pathname)) return NextResponse.next(); - // Relative Location keeps the public host; NextURL.origin is the PM2 bind address. - const location = `/${defaultLocale}${pathname === "/" ? "" : pathname}${request.nextUrl.search}`; - return new NextResponse(null, { - status: 307, - headers: { Location: location }, - }); + // nextUrl.origin is the PM2 bind address (localhost:3024). Use the public Host. + const host = + request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || + request.headers.get("host"); + const proto = + request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || "https"; + const origin = host ? `${proto}://${host}` : request.nextUrl.origin; + const dest = new URL( + `/${defaultLocale}${pathname === "/" ? "" : pathname}`, + origin, + ); + dest.search = request.nextUrl.search; + return NextResponse.redirect(dest); } export const config = {