A Simple URL Redirection Service In Javascript

Bit.ly, TinyUrl, goo.gl... You've probably had an opportunity to use a URL Shortening service in the past, but maybe you want one of your own that allows you to create your own custom shortened URLs with coherant names rather than "http://bit.ly/9SDFH43". Here's how I did it with a small client-side script I added to the index.html for my site 
Just put the following code inside your home page:
<script language="javascript"> var key = window.location.href.split("?")[1].replace("/","") var urls={ 'delicious':'http://www.delicious.com/davidron', 'ssh':"http://sdf.org/ssh", 'blog':"http://blog.davidron.com" } if(key){ if(urls[key]){ window.location.href=urls[key] }else{ document.write("'"+key+"' not found :("); } } </script>

Now, all you have to do is edit that "urls" block to add more redirected URLs. Just make sure that each one except the last one should end with a comma (or else it won't work in IE).

I embedded that code directly in this blog. You can surf to http://blog.davidron.com?ssh and the browser redirects! I redirected http://davidron.com/ to http://blog.davidron.com? so that you can also surf to http://davidron.com/ssh to get to the same redirect.

No comments

Post a Comment