Skip to content

Commit 4032e38

Browse files
committed
feat: add custom 3xx to build
1 parent 1643090 commit 4032e38

File tree

1 file changed

+43
-6
lines changed

1 file changed

+43
-6
lines changed

packages/astro/src/core/build/generate.ts

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -545,16 +545,53 @@ async function generatePath(
545545
if (routeIsRedirect(route) && !config.build.redirects) {
546546
return undefined;
547547
}
548+
548549
const locationSite = getRedirectLocationOrThrow(response.headers);
549550
const siteURL = config.site;
550551
const location = siteURL ? new URL(locationSite, siteURL) : locationSite;
551552
const fromPath = new URL(request.url).pathname;
552-
body = redirectTemplate({
553-
status: response.status,
554-
absoluteLocation: location,
555-
relativeLocation: locationSite,
556-
from: fromPath,
557-
});
553+
554+
const threeXXRoute = matchRoute('/3xx', options.routesList);
555+
556+
if (threeXXRoute) {
557+
const threeXXRenderContext = await RenderContext.create({
558+
pipeline,
559+
pathname: pathname,
560+
request,
561+
routeData: threeXXRoute,
562+
clientAddress: undefined,
563+
});
564+
565+
// Set props for 3xx page
566+
threeXXRenderContext.props = {
567+
status: response.status,
568+
location: locationSite,
569+
from: fromPath,
570+
};
571+
572+
// Render the 3xx page
573+
const redirectResponse = await threeXXRenderContext.render(mod);
574+
let html = await redirectResponse.text();
575+
576+
const delay = response.status === 302 ? 2 : 0;
577+
html = html.replace(
578+
/<head[^>]*>/i,
579+
`$&
580+
<meta http-equiv="refresh" content="${delay};url=${locationSite}">
581+
<meta name="robots" content="noindex">
582+
<link rel="canonical" href="${location}">`,
583+
);
584+
585+
body = html;
586+
} else {
587+
body = redirectTemplate({
588+
status: response.status,
589+
absoluteLocation: location,
590+
relativeLocation: locationSite,
591+
from: fromPath,
592+
});
593+
}
594+
558595
if (config.compressHTML === true) {
559596
body = body.replaceAll('\n', '');
560597
}

0 commit comments

Comments
 (0)