Skip to content

Commit 05099d9

Browse files
Fix broken internal links when served from subdirectory
Internal links in Markdown sources use root-relative paths like /ideas/print-backgrounds/, which break when the site is served from the /csswg-wiki/ subdirectory on GitHub Pages. Add a Jekyll plugin hook that prepends site.baseurl to absolute internal href and src attributes in the rendered HTML. When baseurl is empty (e.g. after switching to the wiki.csswg.org custom domain), the hook is a no-op.
1 parent 8b060cd commit 05099d9

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

_plugins/baseurl_links.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Prepend site.baseurl to absolute internal links in rendered HTML.
2+
#
3+
# Links in Markdown sources use root-relative paths like /ideas/foo/.
4+
# When the site is served from a subdirectory (baseurl: /csswg-wiki),
5+
# these need to become /csswg-wiki/ideas/foo/ in the final HTML.
6+
# When baseurl is empty (custom domain), this is a no-op.
7+
8+
Jekyll::Hooks.register [:pages, :documents], :post_render do |item|
9+
next if item.output_ext != ".html"
10+
11+
baseurl = item.site.config["baseurl"].to_s
12+
next if baseurl.empty?
13+
14+
prefix = Regexp.escape(baseurl.delete_prefix("/"))
15+
16+
item.output = item.output.gsub(
17+
/((?:href|src)=")\/(?!#{prefix}\/|\/)/,
18+
"\\1#{baseurl}/"
19+
)
20+
end

0 commit comments

Comments
 (0)