back

URL Shortening Service in one line of code

I wish I had a convenient one-liner to do things like cook me a burger or clean my bathroom.

Thanks to these babys, at least I'm getting a little closer, but some Open Source firmware would be nice.

On completely different news, URL shortening services suck. They are all run by evil corporations that will do nefarious things with my friends data, best case, or at least I would be a bad friend if I didn't assume that. So I rolled my own, with six lines of code, until I realized I could do it in one, so I did, because I could.

First, get a domain- preferable something short. Mine is capo.casa, and if you have an Italian name, that is the shortest you are going to get, ever. Then set up an Apache server to run it- mine looks like this:

<VirtualHost *:80>
  ServerName capo.casa
  DocumentRoot /var/www/capo.casa
  <Directory /var/www/capo.casa>
    AllowOverride All
  </Directory>
  ErrorLog /var/log/apache2/capo.casa.error.log
  CustomLog /var/log/apache2/capo.casa.access.log combined
</VirtualHost>

OK those were more than one line, but I'm not counting them, because they're an Apache configuration file, and where would we ever get if we counted those towards our one-liners? Here it is:

ssh capocasa.net "echo Redirect 301 /$(< /dev/urandom tr -dc 'a-z' | head -c6) http://something | tee -a /var/www/capo.casa/.htaccess"

Of course you can also put it in a bash script for more convenience

#!/bin/bash

# shorten

TOKEN=$(< /dev/urandom tr -dc 'a-z' | head -c6)
URL=$1

regex='(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]'
string='http://www.google.com/test/link.php'
if ! [[ $URL =~ $regex ]]; then 
  >&2 echo Invalid url: $URL
  exit 
fi
ssh capocasa.net "echo Redirect 301 /$TOKEN $URL >> /var/www/capo.casa/.htaccess"
echo http://capo.casa/$TOKEN

So when I send friends my links, I do it with all the trust in myself and worst assumptions about other people that make me feel warm and fuzzy at night.

$ shorten http://my.cat.videos/kitten-escapes-blender-unharmed
http://capo.casa/ahdebs