Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Developing a URL Shortener

I am trying to develop a URL shortener application for practice with Django. I do not understand how can I create unique strings for each long URL to use as a short URL. Something like other popular URL shorteners do. How can I do this? Is it possible to make all short urls of the same length?

like image 854
User Avatar asked Nov 01 '10 04:11

User


People also ask

How do I create a URL shortener?

To create a URL shortener, we'll need a text input area and a button, then add the script tag. Create the index. php file inside the shorten-url directory and open it using VS code. In folder shorten-url , we will also add script.


2 Answers

  1. I do not understand how can I create unique strings for each long URL to use as a short URL. Something like other popular URL shorteners do.
    As sugerman has said, this is simple, you just create a hash table.

  2. How can I do this?
    There are dynamic ways to do this, but the simplest and most effective is to have a 2 field table in a database, which holds the hashkey and full url. Then your server, like Apache, would have the ability to redirect to the correct page.

  3. Is it possible to make all short urls of the same length?
    Yes, to a certain extent, however once you reach the maximum amount of keys, you would have to reuse/replace the short url IDs. When you set a fixed-length, then you're limiting the amount of possibilities.

My question to you:

I'm under the assumption that by URL shortener you are referring to something like jsFiddle or a pastebin in that they have something like http://jsfiddle.net/sdfj2/. Otherwise, we'd need some more clarification.

like image 137
vol7ron Avatar answered Oct 05 '22 15:10

vol7ron


You'll probably want to create a simple db table mapping a short value to a URL.

The simplest short url you can generate would just be a serial number or autoincrement column (assign the first value 1, then 2 and so on)

It's possible to make all of the URLs of the same length as long until you don't run out of values of the same length, eg if you were using only numbers (as a simple example) it would be from 0000 to 9999.

The magic part would be where you would use mod_rewrite to pass the url to your script as a parameter, have your application look the value up in the db then redirect the user.

This rewrite rule for mod_rewrite will take a URL like example.com/0000 and redirect to example.com/index.py?id=0000 You would put this in .htaccess (I'm assuming you're using apache.)

Your application just reads the id and redirects to the associated page.

RewriteRule ^([0-9]+)/?$ index.py?id=$1 [QSA,L]

If you decide to go with a hash, or a simple base64 serial number (which would be a more compact autoincrement), it would just look slightly different:

RewriteRule ^(.*)/?$ index.py?id=$1 [QSA,L]
like image 23
Kevin Stricker Avatar answered Oct 05 '22 14:10

Kevin Stricker