Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect http to https in twisted

Tags:

https

ssl

twisted

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?

like image 911
alexarsh Avatar asked Jan 20 '23 05:01

alexarsh


1 Answers

To redirect from any given path on HTTP to the same path on the HTTPS (based on Jean-Paul's suggestions in response to my comment):

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

Then you can use RedirectToScheme("https"), in place of your Site() for the HTTP site that you want to redirect from.

Note: If the HTTP that you want to redirect from is on a non-standard port, you will probably have a :<port> part in the the URLRequest that you'll also need to rewrite.

like image 198
rakslice Avatar answered Jan 28 '23 06:01

rakslice