1

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?

1
  • 2
    Well nginx is better suited for this. And gunicorn advise it too: "Gunicorn is a WSGI HTTP server. It is best to use Gunicorn behind an HTTP proxy server. We strongly advise you to use nginx." (taken from the official doc) Commented Mar 30, 2018 at 9:40

2 Answers 2

3

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

The ProxyFix class can now be loaded from werkzeug.middleware.proxy_fix import ProxyFix
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.