From 90266abc91a6b2147aee274e48b16ba5b7147cd6 Mon Sep 17 00:00:00 2001 From: DrMint <29893320+DrMint@users.noreply.github.com> Date: Sun, 28 Jul 2024 08:25:07 +0200 Subject: [PATCH] Remove trailing slash on urls --- astro.config.ts | 1 + src/middleware.ts | 2 ++ src/middleware/removeTrailingSlash.ts | 10 ++++++++++ 3 files changed, 13 insertions(+) create mode 100644 src/middleware/removeTrailingSlash.ts diff --git a/astro.config.ts b/astro.config.ts index 80c2f86..047ad66 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ srcDir: "./src", publicDir: "./public", outDir: "./dist", + trailingSlash: "never", adapter: node({ mode: "standalone", }), diff --git a/src/middleware.ts b/src/middleware.ts index c34df36..69d6178 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -7,11 +7,13 @@ import { actionsHandlingMiddleware } from "src/middleware/actionsHandling"; import { requestTrackingMiddleware } from "src/middleware/requestTracking"; import { pageCachingMiddleware } from "src/middleware/pageCaching"; import { setAstroLocalsMiddleware } from "src/middleware/setAstroLocals"; +import { removeTrailingSlashMiddleware } from "src/middleware/removeTrailingSlash"; export const onRequest = sequence( // Possible redirect actionsHandlingMiddleware, localeNegotiationMiddleware, + removeTrailingSlashMiddleware, addCommonHeadersMiddleware, diff --git a/src/middleware/removeTrailingSlash.ts b/src/middleware/removeTrailingSlash.ts new file mode 100644 index 0000000..1eff2b5 --- /dev/null +++ b/src/middleware/removeTrailingSlash.ts @@ -0,0 +1,10 @@ +import { defineMiddleware } from "astro:middleware"; +import { redirect } from "src/middleware/utils"; + +export const removeTrailingSlashMiddleware = defineMiddleware(({ url }, next) => { + if (url.pathname.endsWith("/")) { + url.pathname = url.pathname.substring(0, url.pathname.length - 1); + return redirect(url.toString()); + } + return next(); +});