Shorten URLs with HAProxy

From CaveLab
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/ -m found
3 http-request redirect location %[capture.req.uri,map(/etc/haproxy/] code 302 if short_url_domain short_url_map


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



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)

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

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

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

sudo pkill -HUP proxy

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