📜 ⬆️ ⬇️

URL rewriting on github pages

I adore GitHub Pages . I use them for everything that is possible and try to avoid server-side code as a plague. I push the 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 redirect to demos on dabblet.com . Any normal person would probably have clenched his teeth and used some 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.html to the repository, any non-existent URL will be redirected to it. Wait a minute, isn't it the same thing we do on the server so that the beautiful URLs can 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 IDs demos and corresponding dabblet urlahs,
  2. 404.html , which either redirects or shows an error
  3. Vanilla JS script that reads a URL, a JSON file and redirects to dabblet.

Here, in fact, JS without 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 <a href="' + url + '">' + url + '</a>…'; 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 human urls for a one-page site, and much more! Is it a hack Of course. But when did it stop us? :)

Source: https://habr.com/ru/post/316790/


All Articles