fix: cleanup pathname with multiple trailing slashes (#1167)

Co-authored-by: John Pope <88814278+innovatedev-john-pope@users.noreply.github.com>
This commit is contained in:
Luca Casonato
2023-05-12 17:34:45 +02:00
committed by GitHub
co-authored by John Pope
parent 4dc6881498
commit 96b89d2a05
2 changed files with 51 additions and 7 deletions
+19 -7
View File
@@ -318,17 +318,14 @@ export class ServerContext {
handlers.errorHandler,
);
return async function handler(req: Request, connInfo: ConnInfo) {
// Redirect requests that end with a trailing slash
// to their non-trailing slash counterpart.
// Ex: /about/ -> /about
// Redirect requests that end with a trailing slash to their non-trailing
// slash counterpart.
const url = new URL(req.url);
if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
url.pathname = url.pathname.slice(0, -1);
if (cleanPathname(url)) {
return Response.redirect(url.href, Status.TemporaryRedirect);
}
// HEAD requests should be handled as GET requests
// but without the body.
// HEAD requests should be handled as GET requests but without the body.
const originalMethod = req.method;
// Internally, HEAD is handled in the same way as GET.
if (req.method === "HEAD") {
@@ -836,3 +833,18 @@ es.addEventListener("message", function listener(e) {
}
});`;
}
/**
* Clean the pathname in the given URL by removing all trailing slashes.
*
* Returns true if the pathname was changed.
*/
export function cleanPathname(url: URL): boolean {
const pathname = url.pathname.replace(/\/+$/, "");
if (pathname === "") return false;
if (pathname !== url.pathname) {
url.pathname = pathname;
return true;
}
return false;
}
+32
View File
@@ -175,6 +175,38 @@ Deno.test("redirect /pages/fresh/ to /pages/fresh", async () => {
);
});
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, Status.TemporaryRedirect);
assertEquals(
resp.headers.get("location"),
"https://fresh.deno.dev/pages/////fresh",
);
});
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, Status.TemporaryRedirect);
assertEquals(
resp.headers.get("location"),
"https://fresh.deno.dev/pages/////fresh",
);
});
Deno.test("no redirect for /pages/////fresh", async () => {
const resp = await router(
new Request("https://fresh.deno.dev/pages/////fresh"),
);
assert(resp);
assertEquals(resp.status, Status.NotFound);
});
Deno.test("/failure", async () => {
const resp = await router(new Request("https://fresh.deno.dev/failure"));
assert(resp);