Wednesday, April 21, 2010

HTTP Redirection

If you need a self-contained web server to handle redirection, you can try this simply Python code. It simple extends the base BaseHTTPServer class.

#! /usr/bin/python


import sys
import BaseHTTPServer


nerror=0
if len(sys.argv) >= 4:

    try:
        port = int(sys.argv[1])
    except:
        nerror += 1

    args = sys.argv[2:]
    if len(args) % 2 == 0:
        mapping = dict( zip(args[::2], args[1::2]) )
    else:
        nerror += 1
else:
    nerror += 1


if nerror > 0:
    sys.stderr.write(\
        "Usage: %s <port> <uri> <redirect> [<uri> <redirect>]" \
        % \
        sys.argv[0])
    exit(0)



class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(s):
        if s.path in mapping:
            url = mapping[s.path]
            s.send_response(302)
            s.send_header('Location', url)
            s.end_headers()
        else:
            s.send_response(200)
            s.send_header('Content-type', 'text/html')
            s.end_headers()
            s.wfile.write("<html><head><title>List of Redirection</title>")
            s.wfile.write("</head><body><h1>List of Redirection</h1><hr>")
            s.wfile.write("<ul>")
            uris = mapping.keys()
            uris.sort()
            for uri in uris:
                redirect = mapping[uri]
                s.wfile.write("<li><a href=%s>%s -> %s</a>" % (redirect,
uri, redirect))
            s.wfile.write("</ul></body></html>")


    # ignore output
    def log_message(s, format, *args):
        pass



if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class(('', port), MyHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()

Launch it like this:

$ ./redirect.py
Usage: ./redirect.py <port> <uri> <redirect> [<uri> <redirect>]

$ ./redirect.py  8080 \
  / http://chihungchan.blogspot.com/ \
  /g http://www.google.com/ \
  /c http://www.cnn.com/ \
  /s http://www.sg/

If you forget what are the short url redirection, simply key in bogus URI

Labels:

1 Comments:

Blogger Maverick said...

Hi, I would like to implement the URL redirection in another file.
That will means that any change in this property file will not affect the source code.

10:26 AM  

Post a Comment

<< Home