[英]How to redirect HTTP requests on a Python App on Bluemix to HTTPS only?
我在Bluemix上安装了python应用程序,并希望仅通过https进行访问。 默认情况下,我可以通过http和https连接。 只想限制通过https的访问。 那么,禁用HTTP访问或仅将请求重定向到https的最佳方法是什么?
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
正如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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.