Zik
Zik

Reputation: 302

how to redirect http to https in flask

I my Flask app to redirect http to https. I found python flask redirect to https from http but it does not work.

from flask import Flask, request, redirect
from werkzeug.serving import make_ssl_devcert


make_ssl_devcert('key')

app = Flask(__name__)

@app.before_request
def before_request():
    if request.url.startswith('http://'):
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)

@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":
    app.run(host='127.0.0.1', port=443, debug=False, ssl_context=('key.crt', 'key.key'))

Upvotes: 0

Views: 6288

Answers (1)

ospider
ospider

Reputation: 10401

First, this should better be done by nginx or whatever you are using in front of flask

For your question, you are listening only on the 443 port not the 80, which is the one http uses, so the http request does not actually hit your server.

Upvotes: 3

Related Questions