1/18/2017 - 6:45 PM

GitHub single-page app hack

GitHub single-page app hack

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.

  // See
    var redirect = sessionStorage.redirect;
    delete sessionStorage.redirect;
    if (redirect && redirect != location.href) {
      history.replaceState(null, null, redirect);
<!doctype html>
    <!-- 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 -->
      sessionStorage.redirect = location.href;
    <meta http-equiv="refresh" content="0;URL=''"></meta>