Skip to content

Instantly share code, notes, and snippets.

@bpsizemore
Created January 25, 2021 13:59
Show Gist options
  • Save bpsizemore/227141941c5075d96a34e375c63ae3bd to your computer and use it in GitHub Desktop.
Save bpsizemore/227141941c5075d96a34e375c63ae3bd to your computer and use it in GitHub Desktop.
Python script to accept requests on port 80 and redirect them to an arbitrary host with a 301
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
import sys
import argparse
def redirect_handler_factory(url):
"""
Returns a request handler class that redirects to supplied `url`
"""
class RedirectHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
def do_POST(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
return RedirectHandler
def main():
parser = argparse.ArgumentParser(description='HTTP redirect server')
parser.add_argument('--port', '-p', action="store", type=int, default=80, help='port to listen on')
parser.add_argument('--ip', '-i', action="store", default="", help='host interface to listen on')
parser.add_argument('redirect_url', action="store")
myargs = parser.parse_args()
redirect_url = myargs.redirect_url
port = myargs.port
host = myargs.ip
redirectHandler = redirect_handler_factory(redirect_url)
handler = SocketServer.TCPServer((host, port), redirectHandler)
print("serving at port %s" % port)
handler.serve_forever()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment