简体   繁体   中英

How to redirect http to https with Gunicorn

I use Flask as Web Application, to redirect http to https, I added such codes in app.py:

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


if __name__ == '__main__':
    app.run()

and the gunicorn command in supervisor.conf is:

command=/home/MyToDo/venv/bin/gunicorn --certfile=/home/MyToDo/SSL/mytodo.vip.cer --keyfile=/home/MyToDo/SSL/mytodo.vip.key -w3 -b0.0.0.0:443 -b0.0.0.0:80 app:app

but when I visit the website, I still need to add "https://" in front the url, it didn't redirect automaticly. So how to make gunicorn redirect http to https, does using Nginx is the only way?

I had the same problem running Flask on Google App Engine Flexible environment with gunicorn. Solved by using werkzeug.contrib.fixers.ProxyFix of Werkzeug version 0.14.1 .

from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)

app.wsgi_app = ProxyFix(app.wsgi_app)

I had the same issues using Google App Engine and have spend too much time on this since all the answers including werkzeug.contrib.fixers.ProxyFix and the official docu's custom HTTPMethodsOverrideMiddleware or other custom solutions did not work for me.

I finally managed to solve this by configuring gunicorn using a config which sets:

secure_scheme_headers = {'X-FORWARDED-PROTO': 'https'} and
forwarded_allow_ips = '*'

Additionally, for the ones wanting to serve static files and who are struggling with unwanted http redirects, adding handlers for each static directory in the .yaml configuration and avoiding nested sub-directories solved this issue.

Flask==2.1.3
gunicorn==20.1.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM