Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
DIY URL Shortener

Do This

  1. Create dedicated domain on an Apache server that supports .htaccess
  2. ssh to root directory there
  3. Use to create 200 random strings. (Five characters long, with digits, uppercase letters and lowercase letters).
  4. Save to short-strings.txt
  5. echo "RewriteRules On" > .htaccess
  6. cat short-strings.txt | awk '{print "RewriteRule ^"$1"$ TO [R,L]"}' >> .htaccess
  7. rm short-strings.txt
  8. When you want to shorten a URL, edit .htaccess. Replace any TO with the long URL.


My shortener is at I already own, so adding a subdomain is easy. I use a dedicated subdomain because I don't want the big .htaccess file to slow down other pages.

These are the first lines in .htaccess at

# enable rewrite rules
RewriteEngine On

# if somebody requests, send them to
RewriteRule ^jzPqF$ [R,L]

# the next short URL I will create is
RewriteRule ^esW7j$ TO [R,L]

How It Works

The key thing is that the short URLs are not serial numbers, like integers from 1-10,000. This would be easy for anybody to spider, and that would be a privacy loss. Using random strings makes them a lot harder to guess, which more or less defeats spiders.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment