如何将Bluemix上Python应用程序上的HTTP请求重定向到仅限HTTPS?

2024-06-16 14:02:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Bluemix上有python应用程序,希望只通过https访问它。默认情况下,我可以通过http和https进行连接。只想通过https限制访问。那么,禁用http访问或只将请求重定向到https的最佳方法是什么?在


Tags: 方法https应用程序http情况重定向bluemix
2条回答

正如他在回答中提到的ralphearle,Bluemix代理服务器终止SSL,因此您可以查看X-Forwarded-Proto报头,以确定请求是来自http还是{}。在

下面是一个基于Bluemix的Python启动程序代码的简单示例。我添加了RedirectHandler类来检查X-Forwarded-Proto头值,并将请求重定向到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()

Bluemix代理服务器终止SSL,因此对应用程序来说,所有流量看起来都像HTTP。但是,代理还添加了一个名为$WSSC的特殊HTTP头,其值可以是HTTP或https。检查此标头,如果值设置为http,则将其更改为https。在

正如Adam在评论中指出的,IBM论坛对这种方法有进一步的讨论:https://developer.ibm.com/answers/questions/16016/how-do-i-enforce-ssl-for-my-bluemix-application.html

相关问题 更多 >