在http中将http重定向到https

ale*_*rsh 4 ssl https twisted

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

rak*_*ice 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
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用RedirectToScheme("https"),代替您Site()要从中重定向的HTTP站点.

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