Ultra-simple Python 2.x CGI URL Shortener on an Apache server

Bit.ly and other URL shorteners make it easy to share a long URL in a short package. Maybe you want to be able to share URLs in the same way using your own domain name. Here are three simple snippets to get you started with URL shortening using Python.

Python script for cgi-bin: redirector.py

#!/usr/bin/env python

import cgi
import cgitb


def redirect():
  query = cgi.FieldStorage(keep_blank_values=True)

  if query.has_key('key'):
    key = query['key'].value
    print "Content-type: text/ascii\n\n"
    print "Error: no key specified"

  links = open('./redirectorLinks.txt').read().strip().splitlines()

  links = eval('{'+','.join(links)+'}')

  if key not in links:
    print "Content-type: text/ascii\n\n"
    print "Error: key not found in list of links"

  print 'Status: 303 See other'
  print "Location:",links[key],'\n\n'



Example text file with redirects: redirectorLinks.txt

This should be placed in the cgi-bin directory.



Example .htaccess mod_rewrite rule

So, for example, rocknawesome.com/go/dovecooing translates to rocknawesome.com/cgi-bin/redirector.py?key=dovecooing. This is the magic that makes this script into a URL shortener. This rule should go in the .htaccess file in your main website directory.

RewriteRule ^go/(.*)$ /cgi-bin/redirector.py?key=$1 [L]



If all you need is a simple shortener, as long as you are messing with the .htaccess file, you could always just do this and skip the Python altogether.

Categories: Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *