1

I'm using Flask to deliver maps designed with folium. I'd like to add a geolocation service, and hence, need to migrate change http to https. I've found a couple of example pages, and the https page delivery works fine. But ... my users still try to connect through http requests, and redirection from http to https does not work.

More precisely, i've added this code to handle http to https conversion:

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

The server initialization works like that :

context = ssl.SSLContext()
context.load_cert_chain('mycert.pem',
                        'myprivkey.pem')
app.run(debug=False, host= '0.0.0.0', port=5051, ssl_context=context)

The url gets printed when I call https pages, but never when I call http pages.

Any clue why the https activation prevents http from working ?

1 Answers1

1

Your Flask server is HTTPS only. When a browser sends an HTTP (non-secure) request but server responds with HTTPS related (handshake etc) response, then browsers like Firefox/Chrome will abort the flow and display something like:

The connection was reset

The connection to the server was reset while the page was loading.

Your Flask is SSL enabled, users trying with http:// will not be reach the step you have provisioned to redirect them to https://.

You could put a reverse proxy listening on both HTTP (80) and HTTPS (443) ports, HTTPS listener will be forwarding the requests to Flask, HTTP listener will be doing the redirection to HTTPS.

ilias-sp
  • 6,135
  • 4
  • 28
  • 41
  • Thanks. I'm note very familiar with reverse proxy. What's the easiest way to achieve this ? – Herve Kabla Oct 12 '22 at 07:17
  • not familiar with all the available options, personally i am using apache for this purpose, but i am sure nginx or other products can do it. for apache here is a [tutorial](https://www.digitalocean.com/community/tutorials/how-to-use-apache-as-a-reverse-proxy-with-mod_proxy-on-ubuntu-16-04) to get you introduced – ilias-sp Oct 12 '22 at 08:33