在http中将http重定向到https

问题描述:

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

I'm running a django app using twisted. I moved now from http to https. How can I add redirects from http to https in twisted?

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

An easy way to generate redirects in Twisted Web is is with the Redirect resource. Instantiate it with a URL and put it into your resource hierarchy. If it is rendered, it will return a redirect response to that 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://*.com/"))

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

这将运行一个响应 http:// localhost:8080 / ,并重定向到 https://*.com/

This will run a server which responds to a request for http://localhost:8080/ with a redirect to https://*.com/.

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

If you're running Django in the WSGI container hosted on an HTTPS server, then you might have code that looks something like this:

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服务器来生成您想要的重定向只需将第一个示例中的一些代码添加到第二个示例中:

You can run an additional HTTP server which generates the redirects you want by just adding some of the code from the first example to this second example:

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()