Back to Home

URL rewriting on GitHub Pages

github · github pages · url rewriting · abnormal programming · 404 · hack

URL rewriting on GitHub Pages

Original author: Lea Verou
  • Transfer
I love GitHub Pages . I use them for everything I can and try to avoid server side code like the plague. I push changes to the repository and they are immediately displayed to users without any hooks or additional steps. Free makes them even more attractive. When it came time to publish my book , naturally, I wanted the accompanying website to be on GitHub Pages.

But there was one problem: I wanted beautiful urls, for example http://play.csssecrets.io/pie-animated , which would be redirected to demos on dabblet.com . Any normal person would most likely bite the bullet and use some kind of server language for this. But I'm not quite normal :)


It turns out that GitHub already uses its own URL rewriting for GitHub Pages : if you add 404.htmlto the repository, any non-existent URL will be redirected to it. Wait a minute, isn’t that the same thing we are doing on the server so that beautiful urls work? We can do exactly the same thing that we do on the server using JavaScript in 404.html!

So, I created:

  1. JSON file with all demo IDs and corresponding dabblet URLs,
  2. 404.html , which either redirects or shows an error
  3. Vanilla JS script that reads URL, JSON file and redirects to dabblet.

Here, in fact, JS without a husk:

(function(){
document.body.className = 'redirecting';
var slug = location.pathname.slice(1);
xhr({
  src: 'secrets.json',
  onsuccess: function () {
    var slugs = JSON.parse(this.responseText);
    var hash = slugs[slug];
    if (hash) {
      // Redirect
      var url = hash.indexOf('http') == 0? hash : 'http://dabblet.com/gist/' + hash;
      $('section.redirecting > p').innerHTML = 'Redirecting to ' + url + '…';
      location.href = url;
    }
    else {
      document.body.className = 'error not-found';
    }
  },
  onerror: function () {
    document.body.className = 'error json';
  }
});
})();

It's all! You can use the same technique to redirect to other HTML pages of GitHub Pages, have humane urls for a one-page site, and much more! Is this a hack? Of course. But when did it stop us? :)

Read Next