Search code examples
pythonhttphttpsibm-cloud

How to redirect HTTP requests on a Python App on Bluemix to HTTPS only?


I have python app on Bluemix and would like to make it accessible over https only. By default I can connect both via http and https. Want to restrict access via https only. So what is the best way to disable http access, or redirect request to https only?


Solution

  • As ralphearle mentioned in his answer, Bluemix proxy server terminates the SSL, so you can look into the X-Forwarded-Proto header to find out if request comes from http or https.

    See below a simple example based on the Python starter code from Bluemix. I added the RedirectHandler class to check for the X-Forwarded-Proto header value and redirects the request to https if it not https.

    import os
    try:
      from SimpleHTTPServer import SimpleHTTPRequestHandler as Handler
      from SocketServer import TCPServer as Server
    except ImportError:
      from http.server import SimpleHTTPRequestHandler as Handler
      from http.server import HTTPServer as Server
    
    class RedirectHandler(Handler):
      def do_HEAD(self):
        if ('X-Forwarded-Proto' in self.headers and 
                self.headers['X-Forwarded-Proto'] != 'https'):
            self.send_response(301)
            self.send_header("Location", 'https://' + self.headers['Host'] + self.path)
            self.end_headers() 
      def do_GET(self):
         self.do_HEAD()
         Handler.do_GET(self)
    
    # Read port selected by the cloud for our application
    PORT = int(os.getenv('PORT', 8000))
    # Change current directory to avoid exposure of control files
    os.chdir('static')
    
    httpd = Server(("", PORT), RedirectHandler)
    try:
      print("Start serving at port %i" % PORT)
      httpd.serve_forever()
    except KeyboardInterrupt:
      pass
    httpd.server_close()