Add the config parameter output.html.site-url to set base url of the 404 page, making links and relative script/css loads behave correctly even in subdirectory paths

This commit is contained in:
Manuel Woelker 2020-06-07 14:14:35 +02:00
parent cda28bb618
commit bff36e7229
4 changed files with 15 additions and 0 deletions

View File

@ -9,6 +9,7 @@ edition = "2018"
[output.html]
mathjax-support = true
site-url = "/"
[output.html.playpen]
editable = true

View File

@ -511,6 +511,8 @@ pub struct HtmlConfig {
pub input_404: Option<String>,
/// Output path for 404.html file, defaults to 404.html, set to "" to disable 404 file output
pub output_404: Option<String>,
/// 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<String>,
/// 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(),
}

View File

@ -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)?;

View File

@ -7,6 +7,10 @@
{{#if is_print }}
<meta name="robots" content="noindex" />
{{/if}}
{{#if base_url}}
<base href="{{ base_url }}">
{{/if}}
<!-- Custom HTML head -->
{{> head}}