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(core): docusaurus serve redirects should include the site /baseUrl/ prefix #10090

Merged
merged 2 commits into from
Apr 30, 2024
Merged
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
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
Loading