Personal site staging.colinozanne.co.uk
portfolio astro
at main 48 lines 1.5 kB view raw
1import { defineMiddleware } from "astro:middleware"; 2import { config, isDev } from "./config.ts"; 3 4export const onRequest = isDev && defineMiddleware((context, next) => { 5 const { url } = context; 6 7 // Get the locale from the domain 8 const host = context.request.headers.get("x-forwarded-host") || 9 context.request.headers.get("host") || 10 url.host; 11 12 // Find which locale this domain corresponds to 13 let domainLocale: string | undefined; 14 for (const [locale, domain] of Object.entries(config.domains)) { 15 const domainHost = new URL(domain as string).host; 16 if (host === domainHost) { 17 domainLocale = locale; 18 break; 19 } 20 } 21 22 // If we're on a domain-mapped locale and the path doesn't start with the locale prefix, 23 // internally rewrite to add the prefix 24 if (domainLocale && url.pathname === "/") { 25 // Rewrite / to /{locale}/ 26 return context.rewrite(`/${domainLocale}/`); 27 } 28 29 // For other paths without locale prefix, also rewrite 30 if ( 31 domainLocale && !url.pathname.startsWith(`/${domainLocale}/`) && 32 !url.pathname.startsWith(`/${domainLocale}`) && 33 !url.pathname.startsWith("/_") 34 ) { 35 // Check if the path starts with any other locale 36 const startsWithOtherLocale = config.locales.some( 37 (l: string) => 38 l !== domainLocale && 39 (url.pathname.startsWith(`/${l}/`) || url.pathname === `/${l}`), 40 ); 41 42 if (!startsWithOtherLocale) { 43 return context.rewrite(`/${domainLocale}${url.pathname}`); 44 } 45 } 46 47 return next(); 48});