How do I redirect a request to a different url in python

tax picture tax · Mar 24, 2010 · Viewed 41.8k times · Source

I have been looking for the syntax to redirect a special url to a remote server to do some XSS testing. Any ideas?

import SimpleHTTPServer
import SocketServer

class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        print self.path 
        if self.path == '/analog':
-------------------->return "http://12b.dk/analog"???
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

theport = 1234
Handler = myHandler
pywebserver = SocketServer.TCPServer(("", theport), Handler)

print "Python based web server. Serving at port", theport
pywebserver.serve_forever()

Answer

Dan Andreatta picture Dan Andreatta · Mar 24, 2010

For a redirect, you have to return a code 301, plus a Location header. Probably you can try something like:

class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
   def do_GET(self):
       self.send_response(301)
       self.send_header('Location','http://www.example.com')
       self.end_headers()