import urllib.request
from urllib.parse import urlsplit

_original = urllib.request.HTTPRedirectHandler.redirect_request

def _same_origin(self, req, fp, code, msg, headers, newurl):
    old, new = urlsplit(req.full_url), urlsplit(newurl)
    if req.has_header('Authorization') and (old.scheme, old.hostname, old.port) != (new.scheme, new.hostname, new.port):
        return None
    return _original(self, req, fp, code, msg, headers, newurl)

urllib.request.HTTPRedirectHandler.redirect_request = _same_origin
