From 15441e316ead89a7cb37d4ac3df64be466ea1cff Mon Sep 17 00:00:00 2001 From: Paul Gottschling Date: Mon, 23 Dec 2024 13:29:48 -0500 Subject: [PATCH] Change redirect logic When Docusaurus detects a section index page - in which the slug matches the second-to-last URL path segment - it produces a route for the page with only the second-to-last path segment, omitting the slug. When migrating to the Docusaurus site, we added redirects from paths with the format `/slug/slug/` to `/slug/`. This change edits these redirects progammatically to reverse the source/destination mappings. If a redirect only maps a Docusaurus-style slug to a pre-migration index page slug, the docs engine rewrites it to map the pre-migration slug to a Docusaurus-style one. For redirect destinations that use pre-migration slugs, this change adjusts them to be Docusaurus-style slugs (this is the current redirect rewriting behavior). --- server/redirects.ts | 44 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/server/redirects.ts b/server/redirects.ts index 6535995..177dcc3 100644 --- a/server/redirects.ts +++ b/server/redirects.ts @@ -14,18 +14,42 @@ export const getRedirects = () => { return result.map((redirect) => { // If a page is an index page for a section, it has the same name as the - // containing subdirectory. If a redirect destination is a menu page, - // rewrite it to point to the containing URL path so Docusaurus recognizes - // it as a valid redirect. - const pathSegs = redirect.destination + // containing subdirectory. Handle this logic to accommodate redirects + // from the previous docs site. + const sourceSegs = redirect.source .replaceAll(new RegExp("/$", "g"), "") .split("/"); - if ( - pathSegs.length >= 2 && - pathSegs[pathSegs.length - 1] == pathSegs[pathSegs.length - 2] - ) { - redirect.destination = - pathSegs.slice(0, pathSegs.length - 2).join("/") + "/"; + + const destSegs = redirect.destination + .replaceAll(new RegExp("/$", "g"), "") + .split("/"); + + // The destination is an index page, since the slug matches the containing + // path segment. + const destIndex = + destSegs.length >= 2 && + destSegs[destSegs.length - 1] == destSegs[destSegs.length - 2]; + + if (!destIndex) { + return { + from: redirect.source, + to: redirect.destination, + }; + } + + const docusaurusDest = + destSegs.slice(0, -1).join("/") + "/"; + + // This redirect maps a Docusaurus-style index page to a previous-site index + // page, so reverse the mapping. + if (redirect.source == docusaurusDest) { + const oldSource = redirect.source; + redirect.source = redirect.destination; + redirect.destination = oldSource; + // This redirect has an old-style index page path as a destination, so + // change it to a Docusaurus-style one. + } else { + redirect.destination = docusaurusDest; } return {