如何仅在 Heroku https 上制作 python? [英] How to make python on Heroku https only?
问题描述
我在 Heroku(Cedar 堆栈)上有 python/django 应用程序,并希望仅通过 https 访问它.我已经启用了ssl piggyback"选项,并且可以通过 https 连接到它.
I have python/django app on Heroku (Cedar stack) and would like to make it accessible over https only. I have enabled the "ssl piggyback"-option, and can connect to it via https.
但是禁用 http 访问或重定向到 https 的最佳方法是什么?
But what is the best way to disable http access, or redirect to https?
推荐答案
将@CraigKerstiens 和@allanlei 的答案结合到我已经测试过并验证可以工作的内容中.当请求是 ssl 时,Heroku 将 HTTP_X_FORWARDED_PROTO 设置为 https,我们可以使用它来检查:
Combining the answer from @CraigKerstiens and @allanlei into something I have tested, and verified to work. Heroku sets the HTTP_X_FORWARDED_PROTO to https when request is ssl, and we can use this to check:
from django.conf import settings
from django.http import HttpResponseRedirect
class SSLMiddleware(object):
def process_request(self, request):
if not any([settings.DEBUG, request.is_secure(), request.META.get("HTTP_X_FORWARDED_PROTO", "") == 'https']):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace("http://", "https://")
return HttpResponseRedirect(secure_url)
这篇关于如何仅在 Heroku https 上制作 python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!