Skip to content

Instantly share code, notes, and snippets.

@mmerickel
Last active June 26, 2017 19:40
Show Gist options
  • Save mmerickel/e77ca7e0665aad171a08 to your computer and use it in GitHub Desktop.
Save mmerickel/e77ca7e0665aad171a08 to your computer and use it in GitHub Desktop.
SSLOnlyMiddleware
setup(
entry_points={
'paste.filter_app_factory': [
'ssl_only = myapp.middlewares.ssl_only:make_filter',
],
}
)
[app:main]
use = egg:myapp
filter-with = egg:myapp#ssl_only
from webob.exc import HTTPMovedPermanently
from webob.dec import wsgify
@wsgify.middleware
def SSLOnlyMiddleware(request, app):
# check that the incoming request was using https
if (
request.scheme != 'https'
and request.headers.get('X-Forwarded-Proto', 'http') != 'https'
):
# redirect the user back using https
https_url = request.url.replace('http://', 'https://')
resp = HTTPMovedPermanently(location=https_url)
resp.cache_expires = 86400
return resp
# override the request scheme to tell the app that we are using https
request.scheme = 'https'
return app
def make_filter(app, global_conf, **filter_settings):
return SSLOnlyMiddleware(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment