From 593f7b0723d757dc312a1f778ae1925c19d75448 Mon Sep 17 00:00:00 2001 From: Claas Augner <495429+caugner@users.noreply.github.com> Date: Wed, 10 Jul 2024 10:44:03 +0200 Subject: [PATCH] fix(cloud-function): avoid double slash where canonical url has trailing slash (#11441) Avoids redirecting `curriculum/index.json` to `curriculum//index.json`. --- .../middlewares/redirect-non-canonicals.ts | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/cloud-function/src/middlewares/redirect-non-canonicals.ts b/cloud-function/src/middlewares/redirect-non-canonicals.ts index a2abc9514822..0c8f1d3eb1b3 100644 --- a/cloud-function/src/middlewares/redirect-non-canonicals.ts +++ b/cloud-function/src/middlewares/redirect-non-canonicals.ts @@ -34,13 +34,23 @@ export async function redirectNonCanonicals( typeof REDIRECTS[source] == "string" && REDIRECTS[source] !== originalSource ) { - const target = REDIRECTS[source] + suffix + parsedUrl.search; - return redirect(res, target, { - status: 301, - cacheControlSeconds: THIRTY_DAYS, - }); + const target = joinPath(REDIRECTS[source], suffix) + parsedUrl.search; + if (pathname !== target) { + return redirect(res, target, { + status: 301, + cacheControlSeconds: THIRTY_DAYS, + }); + } } } next(); } + +function joinPath(a: string, b: string) { + if (a.endsWith("/") && b.startsWith("/")) { + return a + b.slice(1); + } else { + return a + b; + } +}