Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix broken redirect #596

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,16 @@ async function handleRequest(
root: string,
options: WebServerOptions,
) {
const url = new URL(request.url || '/', `http://localhost:${options.port}`);
const pathParts = url.pathname
const requestUrl = new URL(
request.url || '/',
`http://localhost:${options.port}`,
);
const pathParts = requestUrl.pathname
.split('/')
.filter(Boolean)
.map(decodeURIComponent);
const originalPath = path.join(root, ...pathParts);
if (url.pathname.endsWith('/')) {
if (requestUrl.pathname.endsWith('/')) {
pathParts.push('index.html');
}

Expand All @@ -74,12 +77,17 @@ async function handleRequest(
const stats = await fs.stat(localPath);
const isDirectory = stats.isDirectory();
if (isDirectory) {
const redirectUrl = new URL(requestUrl);
if (!redirectUrl.pathname.endsWith('/')) {
redirectUrl.pathname += '/';
}

// This means we got a path with no / at the end!
const document = "<html><body>Redirectin'</body></html>";
response.statusCode = 301;
response.setHeader('Content-Type', 'text/html; charset=UTF-8');
response.setHeader('Content-Length', Buffer.byteLength(document));
response.setHeader('Location', `${request.url}/`);
response.setHeader('Location', redirectUrl.href);
response.end(document);
return;
}
Expand Down
7 changes: 7 additions & 0 deletions test/test.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,11 @@ describe('server', () => {
assert.strictEqual(response.status, 200);
assert.strictEqual(response.data, contents);
});

it('should properly redirect URLs that end with search params', async () => {
const url = `${rootUrl}?a=b`;
const response = await request({url});
assert.strictEqual(response.status, 200);
assert.strictEqual(response.data, contents);
});
});