在http中将http重定向到https

时间:2011-03-15 11:46:32

标签: ssl https twisted

我正在使用twisted运行django应用程序。我现在从http移动到https。如何在http中添加从http到https的重定向?

2 个答案:

答案 0 :(得分:5)

从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")代替您要从中重定向的HTTP站点的Site()

注意:如果要重定向的HTTP位于非标准端口上,则URLRequest中可能还有一个:<port>部分,您还需要重写该部分。

答案 1 :(得分:4)

在Twisted Web中生成重定向的简便方法是使用Redirect资源。使用URL对其进行实例化,并将其放入资源层次结构中。如果它被渲染,它将返回对该URL的重定向响应:

from twisted.web.util import Redirect
from twisted.web.resource import Resource
from twisted.web.server import Site
from twisted.internet import reactor

root = Resource()
root.putChild("foo", Redirect("https://stackoverflow.com/"))

reactor.listenTCP(8080, Site(root))
reactor.run()

这将运行一个服务器,该服务器响应http://localhost:8080/的请求并重定向到https://stackoverflow.com/

如果您在HTTPS服务器上托管的WSGI容器中运行Django,那么您的代码可能如下所示:

from twisted.internet import reactor
from twisted.web.wsgi import WSGIResource
from twisted.web.server import Site
from django import some_wsgi_application_object # Not exactly

root = WSGIResource(reactor, reactor.getThreadPool(), some_wsgi_application_object)
reactor.listenSSL(8443, Site(root), contextFactory)

reactor.run()

您可以运行一个额外的HTTP服务器,通过将第一个示例中的一些代码添加到第二个示例中来生成所需的重定向:

from twisted.internet import reactor
from twisted.web.wsgi import WSGIResource
from twisted.web.util import Redirect
from twisted.web.server import Site
from django import some_wsgi_application_object # Not exactly

root = WSGIResource(reactor, reactor.getThreadPool(), some_wsgi_application_object)
reactor.listenSSL(8443, Site(root), contextFactory)

old = Redirect("https://localhost:8443/")
reactor.listenTCP(8080, Site(old))

reactor.run()