Redirect http to https

Good day!
I can’t figure out how to redirect all http requests to https.
I tried using middleware -

async def force_ssl(request):
    if request.headers.get('X-Forwarded-Proto') == 'http':
        return response.redirect(
            request.url.replace('http://', 'https://', 1),

Unfortunately, it works only sometimes.
Is there a more robust way of forcing SSL to all requests?

It seems like the only time this would happen is if X-Forwarded-Proto doesn’t get set for some reason. Maybe change request.headers.get() to request.scheme ?

Is there any reason why you can’t do this in a proxy like nginx running in front of sanic?

1 Like

Thanks for suggestions.
I think, the problem I am having is with static routes.
Is there a way to redirect static routes? Request middleware does not seem to catch those.

I don’t want to use nginx because I am trying to build standalone application with zero configuration. Pip install and you are ready to go.

I think middleware is still supposed to apply to static routes, but I’ll have to investigate.