Skip to content

Commit

Permalink
Fix redirect edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
lydell committed Jul 2, 2023
1 parent c17d964 commit 85fedb8
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/SimpleStaticFileServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ export function serveStatic(staticDir: AbsolutePath): http.RequestListener {
serveFile(fsPath, stats.size, urlWithoutQuery, request, response);
return;

case "Directory":
case "Directory": {
if (url.endsWith("/")) {
const indexFsPath = `${fsPath}index.html`;
const indexStats = statSync(indexFsPath);
Expand Down Expand Up @@ -427,13 +427,23 @@ export function serveStatic(staticDir: AbsolutePath): http.RequestListener {
return;
}

// When the URL path starts with two or more slashes,
// it’s necessary to specify the host, otherwise it gets treated as
// a protocol relative link.
// Example: http://localhost:1234//node_modules
// Bad: Location: //node_modules/?
// Good: Location: //localhost:1234//node_modules/?
const { host = "localhost" } = request.headers;
response.writeHead(302, {
Location: urlWithoutQuery.endsWith("/")
? `${urlWithoutQuery}?`
: `${urlWithoutQuery}/?`,
Location: `//${host}${
urlWithoutQuery.endsWith("/")
? `${urlWithoutQuery}?`
: `${urlWithoutQuery}/?`
}`,
});
response.end();
return;
}
}
}

Expand Down

0 comments on commit 85fedb8

Please sign in to comment.