After pushing my initial commit to github, I experienced a 404 error when trying to view the github page link. Realized it was due to having used root relative links for every href and src in my project. I need a way to append my github repository name to all href and src.
Any help is appreciated.
within my index.html file I have a script to append my repository name to all src and href - repository name is /Test_App
<script>
$(function () {
$('src').attr('src', '/Test_App').each();
$('href').attr('href', '/Test_App').each();
});
</script>
It's a frustrating problem, isn't it? The solution I use at the moment involves setting up a simple Express node server locally which redirects requests internally in a way that effectively ignores the /${projectName} part at the start of the GitHub Pages URL. With this approach, I can use the same paths as GitHub Pages does when I'm running the project locally and they will work correctly in both environments.
I've documented my approach in my base project repository on GitHub, if you want to take a look. Here is the specific section in the readme about GitHub Pages.
I'm using a .env file and the dotenv project to configure the project name, but you could just as easily hard-code it.
In case that link dies some day, here is the server code I'm using, which is the important part of this solution:
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
const app = express();
const port = process.env.PORT;
const projectName = process.env.PROJECT_NAME;
app.use(express.static('app'));
if (projectName) {
// GitHub Pages publishes projects to <username>.github.io/<projectname>
// This breaks root-relative URLs, so instead use "/projectname/path/" locally
// and resolve it by redirecting it here to a root relative path.
let ghPagesPathPattern = new RegExp(`^/${projectName}/`, 'i');
app.get(ghPagesPathPattern, (req, res) => {
let url = req.url.replace(ghPagesPathPattern, '/');
url = `http://${req.headers.host}${url}`;
res.redirect(url);
});
}
app.listen(port, () => {});
console.log(`Listening on port ${port}`);