diff --git a/book-example/book.toml b/book-example/book.toml index d21c8487..6bb796ca 100644 --- a/book-example/book.toml +++ b/book-example/book.toml @@ -9,6 +9,7 @@ edition = "2018" [output.html] mathjax-support = true +site-url = "/" [output.html.playpen] editable = true diff --git a/src/config.rs b/src/config.rs index 8a8f6ce5..b955e352 100644 --- a/src/config.rs +++ b/src/config.rs @@ -511,6 +511,8 @@ pub struct HtmlConfig { pub input_404: Option, /// Output path for 404.html file, defaults to 404.html, set to "" to disable 404 file output pub output_404: Option, + /// Absolute url to site, used to emit correct paths for the 404 page, which might be accessed in a deeply nested directory + pub site_url: Option, /// This is used as a bit of a workaround for the `mdbook serve` command. /// Basically, because you set the websocket port from the command line, the /// `mdbook serve` command needs a way to let the HTML renderer know where @@ -544,6 +546,7 @@ impl Default for HtmlConfig { git_repository_icon: None, input_404: None, output_404: None, + site_url: None, livereload_url: None, redirect: HashMap::new(), } diff --git a/src/renderer/html_handlebars/hbs_renderer.rs b/src/renderer/html_handlebars/hbs_renderer.rs index b99b83a0..61088218 100644 --- a/src/renderer/html_handlebars/hbs_renderer.rs +++ b/src/renderer/html_handlebars/hbs_renderer.rs @@ -464,6 +464,13 @@ impl Renderer for HtmlHandlebars { let html_content_404 = utils::render_markdown(&content_404, html_config.curly_quotes); let mut data_404 = data.clone(); + let base_url = if let Some(site_url) = &html_config.site_url { + site_url + } else { + warn!("HTML 'site-url' parameter not set, defaulting to '/'. Please configure this to ensure the 404 page work correctly, especially if your site is hosted in a subdirectory on the HTTP server."); + "/" + }; + data_404.insert("base_url".to_owned(), json!(base_url)); data_404.insert("path".to_owned(), json!("404.md")); data_404.insert("content".to_owned(), json!(html_content_404)); let rendered = handlebars.render("index", &data_404)?; diff --git a/src/theme/index.hbs b/src/theme/index.hbs index e8a92dd0..d6e5ce47 100644 --- a/src/theme/index.hbs +++ b/src/theme/index.hbs @@ -7,6 +7,10 @@ {{#if is_print }} {{/if}} + {{#if base_url}} + + {{/if}} + {{> head}}