diff --git a/src/renderer/html_handlebars/helpers/toc.rs b/src/renderer/html_handlebars/helpers/toc.rs
index a3419ce817..58dabf83b2 100644
--- a/src/renderer/html_handlebars/helpers/toc.rs
+++ b/src/renderer/html_handlebars/helpers/toc.rs
@@ -117,7 +117,8 @@ impl HelperDef for RenderToc {
// Hack for windows who tends to use `\` as separator instead of `/`
.replace('\\', "/");
- // Add link
+ // Add link - prepend with / to make it an absolute path from site root
+ out.write("/")?;
out.write(&tmp)?;
out.write(if is_toc_html {
"\" target=\"_parent\">"
diff --git a/tests/testsuite/toc.rs b/tests/testsuite/toc.rs
index eafbdc4857..519faad8d7 100644
--- a/tests/testsuite/toc.rs
+++ b/tests/testsuite/toc.rs
@@ -143,6 +143,29 @@ fn check_link_target_fallback() {
);
}
+// Checks that sidebar links are absolute paths (start with a forward slash).
+#[test]
+fn check_sidebar_links_are_absolute() {
+ let doc = toc_js_html();
+
+ // Find all links in the chapter list
+ let links = doc.find(
+ Class("chapter")
+ .descendant(Name("li"))
+ .descendant(Name("a").and(Class("toggle").not()))
+ );
+
+ // Go through each link and check if its href attribute starts with a slash
+ for link in links {
+ if let Some(href) = link.attr("href") {
+ if !href.is_empty() && !href.starts_with("#") {
+ // Skip anchor links and empty hrefs
+ assert!(href.starts_with("/"), "Link '{}' should be an absolute path starting with '/'.", href);
+ }
+ }
+ }
+}
+
// Checks formatting of summary names with inline elements.
#[test]
fn summary_with_markdown_formatting() {