Go Back

How to build a simple, static URL shortener

I am currently working on some research papers for a small project, and some of the links in the citations are bonkers long. They break over multiple lines and just look extremely unprofessional. In order to fix that, I looked into URL shorteners.

I don't like to depend on 3rd-party services, especially if I need to hand that research paper to a client. What if the service goes out of business? But keeping an actual dynamic reverse proxy or the like running for possibly years is quite a hassle as well. If only there was a way to use static pages for redirecting!

Then I could use Github or Gitlab Pages with a custom domain, and if push comes to shove, I could still move the pages to another service or my own server.

meta http-equiv="refresh"

Enter: <meta http-equiv="refresh" content="0; url='https://www.example.org'" />. This little slice of heaven, placed in the <head> of a webpage, redirects modern user agents to https://www.example.org after 0 seconds. So you could host a exmpl.html next to your static website. This page could have a meta http-equiv="refresh" tag in its <head> which points to the URL. If a user visits https://yourpage.org/exmpl.html their browser gets redirected to the URL in the <meta>-tag.

I wrote a generator that creates redirect files in Node which does exactly that. You can add a list of links into the config.json and run yarn generate. This creates redirect pages for every link in that list.

<!DOCTYPE html>
<html>    
  <head>      
    <title>@@TITLE@@</title>
    <link rel="canonical" href="@@URL@@" />
    <meta name="robots" content="noindex">
    <meta charset="utf-8" />
    <meta http-equiv="refresh" content="0; url='@@URL@@'" />    
  </head>
</html>

It then takes the first 6 chars of the SHA-256 of the URL in base64 and uses it as the shortend URL.

function createShortFileName({url, hashLength}){
  return crypto
    .createHash("sha256")
    .update(url)
    .digest("base64url")
    .slice(0, hashLength);
}

But you can define your own custom function if you wish.

Conclusion

I have a couple of redirects deployed using the domain krz.re (kurz is German for "short"). For example, krz.re/bJj7zH redirects you to a different article of mine. Feel free to use the generator if you want to make your own.