404 When Accessing Root/Leading Slash in GitHub Pages

If you're hitting a 404 Not Found with your assets in GitHub Pages, it might that Pages is different from your development environment. This post goes over a difference I ran into and links to a repo where you can easily see two clear examples of a 200 OK and a 404 Not Found.

404 When Accessing Root/Leading Slash in GitHub Pages

When creating the Procedural Pokémon Building Generation project, I was going great with development until I began work on GitHub pages hosting. I would get 404 errors like:

Errors when using GitHub pages.

If we look specifically at the error for background.png we can see that I was referencing it like:

Referencing a .png but still ran into 404 issues on GitHub Pages.

Locally when I used Live Server for VSCode, it worked just fine and the path made sense to me.

Project structure where background.png is in the correct location under "assets".

It turns out I didn't understand the structure of GitHub pages. As a leading slash will point to a path relative to root I thought it would work just fine, however Pages will have your repo name as a part of the path:

https://<githubName>.github.io/<repoName>/

To take the example earlier, the correct full path to background.png is:

https://nikouu.github.io/procedural-pokemon-buildings/assets/background.png

Meaning if I use a leading slash, the page is attempting to find this from the root:

https://nikouu.github.io/assets/background.png

Which does not include the repo name in the path, thus leading to a 404.

You can see a full example of a leading slash vs a non-leading slash in the repo and GitHub Pages here:

GitHub - nikouu/GitHubPages-Leading-Slash-Examples: Shows the differences in leading slashes in GitHub Pages. https://nikouu.github.io/GitHubPages-Leading-Slash-Examples/
Shows the differences in leading slashes in GitHub Pages. https://nikouu.github.io/GitHubPages-Leading-Slash-Examples/ - GitHub - nikouu/GitHubPages-Leading-Slash-Examples: Shows the differences in...

Oh as a short aside: Open Graph (the metadata for your page) requires absolute URLs - ran into that issue at the same time.