Shorten URLs with HAProxy

From StdOut
This page is currently a draft. Please check back later for additional changes.

I've been looking for a URL shortener to self-host, and there are quite a few to choose from. I wanted something really simply, and didn't need all the tracking and statistics, so I made one. It was fun to make, but over time got more complicated than I needed.

I also found lots of tutorials on how to make a URL shortener, it seems to be a fairly popular thing to build:

I wanted to make something even simpler, so I made a simply script that adds entries to a map file that HAProxy reads. And voila — a URL shortener.

HAProxy config

1 acl short_url_domain hdr(host) -i sho.rt
2 acl short_url_map capture.req.uri,map(/etc/haproxy/redirect.map) -m found
3 http-request redirect location %[capture.req.uri,map(/etc/haproxy/redirect.map)] code 302 if short_url_domain short_url_map

Script

If you don't provide a from path, the script will generate a six character random string to use instead.

#!/bin/bash

DOMAIN="https://sho.rt"

echo -n "From path: /"
read from_path

echo -n "To URL: "
read to_url

if [ -z "$from_path" ]; then
    from_path=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 6 | head -n 1)
fi

if egrep "^/${from_path}\W" /etc/haproxy/redirect.map; then
    echo "Short URL already exists!"
    exit 1
fi

echo "/$from_path $to_url" | sudo tee -a /etc/haproxy/redirect.map > /dev/null
column -t /etc/haproxy/redirect.map | sudo tee /etc/haproxy/redirect.map > /dev/null
#column -t /etc/haproxy/redirect.map | sudo sort -o /etc/haproxy/redirect.map

echo "${DOMAIN}/${from_path}"

sudo pkill -HUP proxy

Then you end up with a /etc/haproxy/redirect.map looking like this:

/github  https://github.com/thomasjsn
/vv9vLR  https://example.com