我正在使用 twisted 运行一个 django 应用程序。我现在从 http 转到 https。如何在扭曲中添加从 http 到 https 的重定向?
最佳答案
从 HTTP 上的任何给定路径重定向到 HTTPS 上的相同路径 (基于 Jean-Paul 针对我的评论提出的建议):
from twisted.python import urlpath
from twisted.web import resource, util
class RedirectToScheme(resource.Resource):
"""
I redirect to the same path at a given URL scheme
@param newScheme: scheme to redirect to (e.g. https)
"""
isLeaf = 0
def __init__(self, newScheme):
resource.Resource.__init__(self)
self.newScheme = newScheme
def render(self, request):
newURLPath = request.URLPath()
# TODO Double check that == gives the correct behaviour here
if newURLPath.scheme == self.newScheme:
raise ValueError("Redirect loop: we're trying to redirect to the same URL scheme in the request")
newURLPath.scheme = self.newScheme
return util.redirectTo(newURLPath, request)
def getChild(self, name, request):
return self
然后你可以使用RedirectToScheme("https")
, 代替你的 Site()
对于您要从中重定向的 HTTP 站点。
注意:如果您要重定向的 HTTP 是在非标准端口上,您可能会有一个 :<port>
您还需要重写的 URLRequest 部分。
关于ssl - 将 http 重定向到扭曲的 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5311229/