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

cgitb.enable()

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

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

  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"
    quit()

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

redirect()

 

Example text file with redirects: redirectorLinks.txt

This should be placed in the cgi-bin directory.

'dovesquawking':'http://www.xeno-canto.org/95790'
'dovecooing':'http://www.xeno-canto.org/270553'
'resume-dev':'http://rocknawesome.com/files/Krohse,%20Joshua%20-%202017%20Developer%20Resume.pdf'

 

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]

 

Postscript

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 *