-
-
Save mauro-balades/cefb72f6b52d25f55a3dffd5d3c80ace to your computer and use it in GitHub Desktop.
WSGI middleware to redirect incoming http requests to https. This is not original, but I can't remember where I first found it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib import quote | |
class SSLRedirect(object): | |
def __init__(self,app): | |
self.app=app | |
def __call__(self,environ,start_response): | |
proto = environ.get('HTTP_X_FORWARDED_PROTO') or environ.get('wsgi.url_scheme', 'http') | |
if proto=='https': | |
return self.app(environ,start_response) | |
else: | |
url = 'https://' | |
if environ.get('HTTP_HOST'): | |
url += environ['HTTP_HOST'] | |
else: | |
url += environ['SERVER_NAME'] | |
url += quote(environ.get('SCRIPT_NAME', '')) | |
url += quote(environ.get('PATH_INFO', '')) | |
if environ.get('QUERY_STRING'): | |
url += '?' + environ['QUERY_STRING'] | |
status = "301 Moved Permanently" | |
headers = [('Location',url),('Content-Length','0')] | |
start_response(status,headers) | |
return [''] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment