Skip to content

Commit

Permalink
fix(core): docusaurus serve redirects should include the site `/bas…
Browse files Browse the repository at this point in the history
…eUrl/` prefix (#10090)
  • Loading branch information
slorber authored Apr 30, 2024
1 parent 0b49e6c commit 3ee7760
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions packages/docusaurus/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@ import logger from '@docusaurus/logger';
import {DEFAULT_BUILD_DIR_NAME} from '@docusaurus/utils';
import serveHandler from 'serve-handler';
import openBrowser from 'react-dev-utils/openBrowser';
import {applyTrailingSlash} from '@docusaurus/utils-common';
import {loadSiteConfig} from '../server/config';
import {build} from './build';
import {getHostPort, type HostPortOptions} from '../server/getHostPort';
import type {LoadContextParams} from '../server/site';

function redirect(res: http.ServerResponse, location: string) {
res.writeHead(302, {
Location: location,
});
res.end();
}

export type ServeCLIOptions = HostPortOptions &
Pick<LoadContextParams, 'config'> & {
dir?: string;
Expand Down Expand Up @@ -62,15 +70,24 @@ export async function serve(
const server = http.createServer((req, res) => {
// Automatically redirect requests to /baseUrl/
if (!req.url?.startsWith(baseUrl)) {
res.writeHead(302, {
Location: baseUrl,
});
res.end();
redirect(res, baseUrl);
return;
}

// We do the redirect ourselves for a good reason
// server-handler is annoying and won't include /baseUrl/ in redirects
const normalizedUrl = applyTrailingSlash(req.url, {trailingSlash, baseUrl});
if (req.url !== normalizedUrl) {
redirect(res, normalizedUrl);
return;
}

// Remove baseUrl before calling serveHandler, because /baseUrl/ should
// serve /build/index.html, not /build/baseUrl/index.html (does not exist)
// Note server-handler is really annoying here:
// - no easy way to do rewrites such as "/baseUrl/:path" => "/:path"
// - no easy way to "reapply" the baseUrl to the redirect "Location" header
// See also https://github.com/facebook/docusaurus/pull/10090
req.url = req.url.replace(baseUrl, '/');

serveHandler(req, res, {
Expand Down

0 comments on commit 3ee7760

Please sign in to comment.