【问题标题】:How to redirect HTTP requests on a Python App on Bluemix to HTTPS only?如何仅将 Bluemix 上 Python 应用程序上的 HTTP 请求重定向到 HTTPS?
【发布时间】:2015-12-08 23:21:59
【问题描述】:

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

【问题讨论】:

标签: python http https ibm-cloud


【解决方案1】:

正如ralphearle 在他的回答中提到的那样,Bluemix 代理服务器会终止 SSL,因此您可以查看X-Forwarded-Proto 标头以了解请求是来自http 还是https

请参见下面的一个简单示例,该示例基于来自 Bluemix 的 Python 起始代码。我添加了RedirectHandler 类来检查X-Forwarded-Proto 标头值,如果不是https,则将请求重定向到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()

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 最好检查 X-Forwarded-Proto 标头。
    猜你喜欢
    • 2012-10-24
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2016-07-06
    • 2018-02-08
    • 2023-03-28
    相关资源
    最近更新 更多