Skip to content

Instantly share code, notes, and snippets.

@mauro-balades
Forked from devries/ssl_redirect.py
Created November 28, 2021 17:11
Show Gist options
  • Save mauro-balades/cefb72f6b52d25f55a3dffd5d3c80ace to your computer and use it in GitHub Desktop.
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.
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