Skip to content

Commit 53f4b22

Browse files
committed
fix for trailing slash in versions not redirecting
1 parent 088d850 commit 53f4b22

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

netlify/edge-functions/redirect-to-latest.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,26 @@ export default async (request: Request, context) => {
1111
const redirectableSections = ['/', '/about', '/blog', '/get-involved', '/news', '/search'];
1212
const versionPath = versionMatch[0]; // ex /v1.15
1313
const remainder = pathname.slice(versionPath.length) || '/';
14-
// Check if the remainder starts with a language code
15-
const languageCodeMatch = remainder.match(/^\/([a-z]{2})\//);
14+
// Check if the remainder starts with an optional leading slash followed by a language code
15+
const languageCodeMatch = remainder.match(/^\/?([a-z]{2})(\/|$)/);
1616
let languageCode: string | null = null;
17-
let sectionPath: string = remainder;
17+
let remainingPathAfterLang = remainder;
1818

1919
if (languageCodeMatch) {
2020
languageCode = languageCodeMatch[1];
21-
sectionPath = remainder.slice(languageCodeMatch[0].length) || '/'; // slice to remove the leading slash of the language code
21+
remainingPathAfterLang = remainder.slice(languageCodeMatch[0].length);
2222
}
23-
// Check if the base section (after removing language code) is redirectable
23+
// If there's a language code and no further path, redirect to the homepage with the language code
24+
if (languageCode && remainingPathAfterLang === '') {
25+
return Response.redirect(new URL(`/latest/${languageCode}/`, url.origin), 301);
26+
}
27+
// Check if the remaining path (after version and optional language code) starts with a redirectable section
2428
const shouldRedirect = redirectableSections.some(section =>
25-
sectionPath === section || sectionPath.startsWith(`${section}/`) || (section === '/' && sectionPath === ''));
29+
remainingPathAfterLang === section || remainingPathAfterLang.startsWith(`${section}/`) || (section === '/' && remainingPathAfterLang === ''));
2630

2731
if (shouldRedirect) {
28-
const cleanSectionPath = sectionPath.startsWith('/') ? sectionPath.substring(1) : sectionPath;
29-
const newPath = `/latest/${cleanSectionPath}`; // English path doesn't include language code
32+
const cleanRemainderPath = remainingPathAfterLang.startsWith('/') ? remainingPathAfterLang.substring(1) : remainingPathAfterLang;
33+
const newPath = `/latest/${languageCode ? `${languageCode}/` : ''}${cleanRemainderPath}`;
3034
return Response.redirect(new URL(newPath, url.origin), 301);
3135
}
3236
// For version-specific paths we want to keep, tell Netlify to stop processing this function

0 commit comments

Comments
 (0)