Explain Codes LogoExplain Codes Logo

Github pages and relative paths

html
relative-paths
github-pages
jekyll
Alex KataevbyAlex Kataev·Dec 14, 2024
TLDR

To rectify path discrepancies on GitHub Pages, implement root-relative URLs. Use this format: /repo-name/ when writing relative links. This will ensure your files are correctly linked.

Example for a repository named my-repo:

<!-- Make sure the image is not eaten by Pac-Man --> <img src="/my-repo/images/logo.png" alt="Logo"> <!-- CSS, the fashion designer of the web --> .url('/my-repo/styles/main.css');

Update /repo-name/ to correspond to your exact repository name.

Jekyll: Your assistant for URL management

Given the dynamic nature of Jekyll, setting the baseurl in _config.yml to /project-name is crucial. When referencing assets, use {{ site.baseurl }} to ensure your paths don't get lost in the matrix, both locally and when deployed.

baseurl: "/my-project" # The name's Project, My Project!

To serve locally with Jekyll:

jekyll serve --baseurl=""

This simulates the GitHub Pages environment, creating harmony between your local setup and the live site.

Let <base> tag lead the way

Add the <base> tag within the HTML <head> to maintain the correct paths:

<head> <!-- FYI, this is where I'm based --> <base href="/my-repo/"> </head>

Match this with {{ site.baseurl }} when working with Jekyll.

Troubleshooting GitHub Pages

Steer away from absolute paths; they can crack under pressure and lead to broken links on GitHub Pages. Break this pattern by meticulously organizing your directories — maintain a uniform folder structure for intuitive navigation.

Remember the rules of GitHub Pages caching: expect an up-to-15-minute window for changes to refresh.

Learning from others: Bootstrap and plugins

Take clues from existing frameworks. For example, Twitter Bootstrap structures links optimally for compatibility in any environment.

Consider the Jekyll Relative Links plugin. It adeptly converts relative links in Markdown files to persistent links.

Preview before launch

Always test your changes in a local environment (a necessary dress rehearsal). A local server is a truthful mirror — show your GitHub Pages site its reflection.

Fear not, your GitHub Pages can serve right from your master branch.