Categories
Computers Linux Web design

Your own URL shortener

I use mostly bit.ly for shortening URLs but sometimes you don’t want to be dependent upon a public site, even if it is big and popular. I needed to install a custom URL shortener and this is what I did.

Firstly, my requirements were that it should be lightweight and simple. I didn’t expect that many hits on the URLs and even though I am a big fan of Ruby on Rails the idea of spinning up a Rails site just to dish out a HTTP redirect didn’t sound like a great idea. Instead I went for PHP backed by a MySQL database.

Now, searching for URL shorteners written in PHP results in a large number of hits and it can be pretty daunting to know which to pick. Shortly and Yourls were frequently present in listings of popular shorteners so I decided to setup those and benchmark them. However, the Shortly web site turned out to be unavailable so in the end I settled on just installing Yourls.

Yourls supports both public and private mode of operation. In private mode a password is required to administer it. In my case I wanted to make it simple and allow everyone at the company to manage the URLs but disallow access to the management facilities from the Internet. However, Internet users still need to be able to resolve the URLs. I solved this via conditional rewrites in the Apache configuration, like so:

	Alias /s/ "/srv/www/shortener/"
	RewriteCond %{REQUEST_URI} ^/s/admin
	RewriteCond %{REMOTE_ADDR} !^192\.168\.(\d+)\.(\d+)$
	RewriteRule ^/.*$ - [F]
	RewriteCond %{REQUEST_URI} \+$
	RewriteCond %{REMOTE_ADDR} !^192\.168\.(\d+)\.(\d+)$
	RewriteRule ^/.*$ - [F]
	RewriteCond %{REQUEST_URI} ^/s/[index.php]?$
	RewriteCond %{REMOTE_ADDR} !^192\.168\.(\d+)\.(\d+)$
	RewriteRule ^/.*$ - [F]

The above is from the config file for the corporate web site, lodging the URL shortening under the /s/ subdirectory of the web site. There are three rewrite rules:

  • Preventing access to the admin pages for external clients
  • Preventing access to the link statistics for external clients
  • Preventing access to the link creating page for external clients

By default Yourls will create sequential links starting from one and going up. This makes it trivial to guess other links which is not what I wanted. Fortunately, it turned out to be very simple to create random links by following the instructions found on this page.

I am quite happy with the result. I wish the default web GUI would come with different themes but since it is only used when administering the links it doesn’t really matter. I will continue to use bit.ly but Yourls is definitely a keeper.

css.php