Skip to content

Instantly share code, notes, and snippets.

@niisar
Created January 18, 2017 18:45
Show Gist options
  • Save niisar/d317285fa413c2a2ce318705a10b8eb3 to your computer and use it in GitHub Desktop.
Save niisar/d317285fa413c2a2ce318705a10b8eb3 to your computer and use it in GitHub Desktop.
GitHub single-page app hack
<!doctype html>
<html>
<head>
<!-- This stores the URL the user was attempting to go to in sessionStorage,
and then redirects all 404 responses to the app’s index.html page -->
<!-- See http://www.backalleycoder.com/2016/05/13/sghpa-the-single-page-app-hack-for-github-pages/ -->
<script>
sessionStorage.redirect = location.href;
</script>
<meta http-equiv="refresh" content="0;URL='https://USERNAME.github.io/PROJECT_NAME'"></meta>
</head>
<body>
</body>
</html>

GitHub Pages redirects all 404 requests to a 404.html page, which you can configure to handle all 404 requests for your static sites. What Buchner discovered is that if you make your 404.html page redirect to your index.html page using a tag, and at the same time store off the URL the user was attempting to go to, you can return them to that location with a little snippet of code in your index.html file.

Here’s what that looks like in action. First here’s the 404.html page that you’ll want to use. If you’re using the Angular CLI you’ll want to place this at src/404.html.

Next, include the snippet below in the of your index.html file, which takes the stored URL from session storage, and uses the browser’s replaceState() API to redirect the user back to the URL they were attempting to go to in the first place.

<script>
// See http://www.backalleycoder.com/2016/05/13/sghpa-the-single-page-app-hack-for-github-pages/
(function(){
var redirect = sessionStorage.redirect;
delete sessionStorage.redirect;
if (redirect && redirect != location.href) {
history.replaceState(null, null, redirect);
}
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment