How URL shorteners work
URL shortening, sometimes called link shortening, is used to shorten long and nasty URLs into something more readable and shareable.
At its very essence, a URL shortener is a link that 301 redirects into a new destination.
Algorithms for Link Shortening
When you create a short-link with any link shortening service (be it Linkly, Bitly, or any of a number of others), a new link is inserted into a database, which returns a numeric ID.
This number might be very long, and numbers certainly aren’t very attractive on the end of URLs: e.g.
shor.tr/2385162034
Link shorteners get around this by changing the base of the number.
In base 10, numbers go from 0 to 9 before you add another digit (10) and start all over again.
In base 16 (hexadecimal), numbers go from 0-15, however the numbers 10-15 are represented by the letters A through F.
So, for example, the number 11 would be B.
The long number in the link above would be 8E2AAF32 - a bit shorter, but not much shorter.
Link shorteners tend to use Base 62, which gives you:
- The numbers 0-9 (10 symbols)
- The lowercase letters a - z (26 symbols)
- The uppercase letters A - Z (26 symbols)
For a total of 10 + 26 + 26 = 62 symbols.
Now, let’s encode the number above using Base 62:
2385162034 in Base 10 = 2bPtb0 in Base 62
This is now six characters (as opposed to 10), yet still uniquely identifies the link.
All link shorteners work on similar principles.
After the shortening…
When a request comes for a link, the extension is converted back to Base 10, the database queried for that link ID, and the user is redirected to the destination for that link.
A link shortener might at this point record the request, in order to provide click tracking functionality.