diff --git a/src/server/context.ts b/src/server/context.ts index 8fa75235..5b90d2fb 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -142,6 +142,14 @@ export class ServerContext { const inner = router.router(this.#routes()); const middleware = this.#middleware; return function handler(req: Request) { + // Redirect requests that end with a trailing slash + // to their non-trailing slash counterpart. + // Ex: /about/ -> /about + const url = new URL(req.url); + if (url.pathname.length > 1 && url.pathname.endsWith("/")) { + url.pathname = url.pathname.slice(0, -1); + return Response.redirect(url, 307); + } const handle = () => Promise.resolve(inner(req)); return middleware.handler(req, handle); }; diff --git a/tests/main_test.ts b/tests/main_test.ts index b2a46990..75dfe3e6 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -139,3 +139,13 @@ Deno.test("/books/:id page - /books/abc", async () => { assert(resp); assertEquals(resp.status, 404); }); + +Deno.test("redirect /pages/fresh/ to /pages/fresh", async () => { + const resp = await router(new Request("https://fresh.deno.dev/pages/fresh/")); + assert(resp); + assertEquals(resp.status, 307); + assertEquals( + resp.headers.get("location"), + "https://fresh.deno.dev/pages/fresh", + ); +});