[英]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.