I made a simple script that adds entries to a map file — which HAProxy reads. And voila — a URL shortener! 👇
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:
- Make a SUPER simple personal URL shortener with Netlify
- How To Build A URL Shortener With Node.js, Express, and MongoDB
I wanted to make something even simpler, so I made a small bash script that adds entries to a map file which HAProxy reads. And voila — a URL shortener.
HAProxy config
acl short_url_domain hdr(host) -i sho.rt
acl short_url_map capture.req.uri,map(/etc/haproxy/redirect.map) -m found
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"
tmpfile=$(mktemp /tmp/redirect-map.XXXXXX)
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 | tee $tmpfile > /dev/null
sudo mv $tmpfile /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
Last commit 2024-11-11, with message: Add lots of tags to posts.