Skip to content

Instantly share code, notes, and snippets.

@devries
Last active March 24, 2022 09:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save devries/4a747a284e75a5d63f93 to your computer and use it in GitHub Desktop.
Save devries/4a747a284e75a5d63f93 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