How do I redirect a request to a different url in python
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()
Python 3
In python3
it is done very similar to other answers, but different enough to justify demonstration.
This is a script that does nothing but listen on the port passed as argument 1 and send a 302 ("Found" aka Temporary) redirect to the URL passed as argument 2. (And it has a usage message.)
#!/usr/bin/env python3import sysfrom http.server import HTTPServer, BaseHTTPRequestHandlerif len(sys.argv)-1 != 2: print("""Usage: {} <port_number> <url> """.format(sys.argv[0])) sys.exit()class Redirect(BaseHTTPRequestHandler): def do_GET(self): self.send_response(302) self.send_header('Location', sys.argv[2]) self.end_headers()HTTPServer(("", int(sys.argv[1])), Redirect).serve_forever()
You call it like:
sudo ./redirect.py 80 http://jenkins.example.com:8080/
That example ought to give you enough to write what ever kind of function you need.
This is a complete piece of code to redirect, save this file and run it as a python program. to terminate, ctrl + c.
import SimpleHTTPServerimport SocketServerclass myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): print self.path self.send_response(301) new_path = '%s%s'%('http://newserver.com', self.path) self.send_header('Location', new_path) self.end_headers()PORT = 8000handler = SocketServer.TCPServer(("", PORT), myHandler)print "serving at port 8000"handler.serve_forever()