Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

How to run your own link shortener on Jekyll

#jekyll

I wanted to have the ability to use short links to external resources. I also wanted to be able to change the targets of the links.

I suppose that it would have been possible with some link shortener but I didn’t want to pay for it and I wanted to have some sort of privacy.

Instead I made use of the Jekyll jekyll-datapage-generator to accomplish this quite well.

Once the gem is installed and added to the plugins:, I added the following in config.yml:

page_gen:
- data: 'links'
  template: 'redirect'
  dir: 'r'
  index_files: false
  name: 'slug'
  title: 'name'

In the _data directory, I added a JSON file called links.json that had the following structure:

[
  {
    "name": "Google",
    "link": "https://google.com",
    "slug": "google"
  }
]

(I chose JSON but it supports YAML and CSV as well.)

Then I created the redirect.html in _layouts:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Redirecting&hellip;</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&display=swap" rel="stylesheet">
  <link href="/assets/css/style.css" rel="stylesheet">
  <link rel="canonical" href="{{ page['link'] }}">
  <script>location="{{ page['link'] }}"</script>
  <meta http-equiv="refresh" content="0; url={{ page['link'] }}">
  <meta name="robots" content="noindex">
</head>
<body class='page '>
  {% include main-menu-mobile.html %}
  <div id="wrapper" class="wrapper">
    {% include header.html headerClass='header-extra' %}
    <div class="container pb-6 pt-6 pt-md-10 pb-md-10">
      <div class="row justify-content-start">
        <h1 style="display: block; width: 100%;">Redirecting&hellip;</h1>
        <a href="{{ page['link'] }}">Click here if you are not redirected.</a>
      </div>
    </div>
  </div>
  {% include footer.html %}
  {% include sub-footer.html %}
</body>
</html>

This results in links that look like this: http://localhost:4000/r/google that would very quickly redirect to https://google.com. In case it fails for whatever reason it’d show the typical “Click here if you are not redirected.” link.