Skip to content

Commit 2554834

Browse files
committed
Add canonical-site-url setting
Based on the conversation in #1238, this implements the suggestion by markhildreth to implement such a setting. I've additionally infixed `-site-` to highlight the relationship with the `site-url`, and to distinguish it from the canonical URL as it occurs in a page.
1 parent 780fd83 commit 2554834

File tree

7 files changed

+62
-0
lines changed

7 files changed

+62
-0
lines changed

crates/mdbook-core/src/config.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,8 @@ pub struct HtmlConfig {
459459
pub input_404: Option<String>,
460460
/// Absolute url to site, used to emit correct paths for the 404 page, which might be accessed in a deeply nested directory
461461
pub site_url: Option<String>,
462+
/// Canonical site url, used to emit <link rel="canonical"> tags in the HTML.
463+
pub canonical_site_url: Option<String>,
462464
/// The DNS subdomain or apex domain at which your book will be hosted. This
463465
/// string will be written to a file named CNAME in the root of your site,
464466
/// as required by GitHub Pages (see [*Managing a custom domain for your
@@ -512,6 +514,7 @@ impl Default for HtmlConfig {
512514
git_repository_icon: None,
513515
input_404: None,
514516
site_url: None,
517+
canonical_site_url: None,
515518
cname: None,
516519
edit_url_template: None,
517520
live_reload_endpoint: None,

crates/mdbook-html/front-end/templates/index.hbs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
{{#if base_url}}
1111
<base href="{{ base_url }}">
1212
{{/if}}
13+
{{#if canonical_url}}
14+
<link rel="canonical" href="{{ canonical_url }}">
15+
{{/if}}
1316

1417

1518
<!-- Custom HTML head -->

crates/mdbook-html/src/html_handlebars/hbs_renderer.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@ impl HtmlHandlebars {
6464
.to_str()
6565
.with_context(|| "Could not convert path to str")?;
6666
let filepath = Path::new(&ctx_path).with_extension("html");
67+
let filepath_str = filepath
68+
.to_str()
69+
.with_context(|| format!("Could not convert path to str: {}", filepath.display()))?;
70+
let canonical_url = ctx.html_config.canonical_site_url.map(|canon_url| {
71+
let canon_url = canon_url.as_str().trim_end_matches('/');
72+
format!("{}/{}", canon_url, self.clean_path(filepath_str))
73+
});
6774

6875
let book_title = ctx
6976
.data
@@ -80,6 +87,8 @@ impl HtmlHandlebars {
8087
};
8188

8289
ctx.data.insert("path".to_owned(), json!(path));
90+
ctx.data
91+
.insert("canonical_url".to_owned(), json!(canonical_url));
8392
ctx.data.insert("content".to_owned(), json!(content));
8493
ctx.data.insert("chapter_title".to_owned(), json!(ch.name));
8594
ctx.data.insert("title".to_owned(), json!(title));
@@ -298,6 +307,15 @@ impl HtmlHandlebars {
298307

299308
Ok(())
300309
}
310+
311+
/// Strips `index.html` from the end of a path, if it exists.
312+
fn clean_path(&self, path: &str) -> String {
313+
if path == "index.html" || path.ends_with("/index.html") {
314+
path[..path.len() - 10].to_string()
315+
} else {
316+
path.to_string()
317+
}
318+
}
301319
}
302320

303321
impl Renderer for HtmlHandlebars {

guide/src/format/configuration/renderers.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,12 @@ The following configuration options are available:
161161
navigation links and script/css imports in the 404 file work correctly, even when accessing
162162
urls in subdirectories. Defaults to `/`. If `site-url` is set,
163163
make sure to use document relative links for your assets, meaning they should not start with `/`.
164+
- **canonical-site-url:** Set the canonical URL for the book, which is used by
165+
search engines to determine the primary URL for the content. Use this when
166+
your site is deployed at multiple URLs. For example, when you have site
167+
deployments for a range of versions, you can point all of them to the URL for
168+
the latest version. Without this, your content may be penalized for
169+
duplication, and visitors may be directed to an outdated version of the book.
164170
- **cname:** The DNS subdomain or apex domain at which your book will be hosted.
165171
This string will be written to a file named CNAME in the root of your site, as
166172
required by GitHub Pages (see [*Managing a custom domain for your GitHub Pages

tests/testsuite/rendering.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,3 +223,25 @@ Html text was:
223223
fn html_blocks() {
224224
BookTest::from_dir("rendering/html_blocks").check_all_main_files();
225225
}
226+
227+
// Checks that a canonical URL is generated correctly.
228+
#[test]
229+
fn canonical_url() {
230+
BookTest::from_dir("rendering/canonical_url")
231+
.check_file_contains(
232+
"book/index.html",
233+
"<link rel=\"canonical\" href=\"https://example.com/test/\">",
234+
)
235+
.check_file_contains(
236+
"book/canonical_url.html",
237+
"<link rel=\"canonical\" href=\"https://example.com/test/canonical_url.html\">",
238+
)
239+
.check_file_contains(
240+
"book/nested/page.html",
241+
"<link rel=\"canonical\" href=\"https://example.com/test/nested/page.html\">",
242+
)
243+
.check_file_contains(
244+
"book/nested/index.html",
245+
"<link rel=\"canonical\" href=\"https://example.com/test/nested/\">",
246+
);
247+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[book]
2+
title = "canonical_url test"
3+
4+
[output.html]
5+
# trailing slash is not necessary or recommended, but tested here
6+
canonical-site-url = "https://example.com/test/"
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
- [Intro](README.md)
2+
- [Canonical URL](canonical_url.md)
3+
- [Nested Page](nested/page.md)
4+
- [Nested Index](nested/index.md)

0 commit comments

Comments
 (0)