Skip to content

Commit 4bff912

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 3fa4921 commit 4bff912

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
@@ -229,3 +229,25 @@ fn html_blocks() {
229229
fn code_block_fenced_with_indent() {
230230
BookTest::from_dir("rendering/code_blocks_fenced_with_indent").check_all_main_files();
231231
}
232+
233+
// Checks that a canonical URL is generated correctly.
234+
#[test]
235+
fn canonical_url() {
236+
BookTest::from_dir("rendering/canonical_url")
237+
.check_file_contains(
238+
"book/index.html",
239+
"<link rel=\"canonical\" href=\"https://example.com/test/\">",
240+
)
241+
.check_file_contains(
242+
"book/canonical_url.html",
243+
"<link rel=\"canonical\" href=\"https://example.com/test/canonical_url.html\">",
244+
)
245+
.check_file_contains(
246+
"book/nested/page.html",
247+
"<link rel=\"canonical\" href=\"https://example.com/test/nested/page.html\">",
248+
)
249+
.check_file_contains(
250+
"book/nested/index.html",
251+
"<link rel=\"canonical\" href=\"https://example.com/test/nested/\">",
252+
);
253+
}
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)