How To Fix HTTP Redirect In Flask
Today I encountered a problem in Flask, that caused my links to be not found.
After googling and an hour of trial and error, I finally found a solution. Here it is.
Solution To HTTP Redirect Instead Of HTTPS
In the NGINX configuration file add this parameter proxy_set_header X-Forwarded-HTTPS on; under the location section
location @proxy_to_app {
proxy_pass http://myweb.local:5000; # <- let nginx pass traffic to the gunicorn server
proxy_ssl_server_name on;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-HTTPS on; # Fix logout url for redirects to http instead of https
}
Now every time I click on the link, that was created by using URL_FOR Redirect syntax, I go straight to the correct HTTPS URL.
Failed Solution On StackOverflow
It took me an hour to go through all kinds of answers. Below are the ones, that didn't work for me.
External = True
using _external=True inside url_for
Preferred URL Scheme
app.config.update(dict(
PREFERRED_URL_SCHEME = 'https'
))
Nginx Forwarded Proto Scheme
proxy_set_header X-Forwarded-Proto $scheme;
Enforce URL Scheme
def _force_https(app):
def wrapper(environ, start_response):
environ['wsgi.url_scheme'] = 'https'
return app(environ, start_response)
return wrapper
app = Flask(...)
app = _force_https(app)
Conclusion
If you want your links to use HTTPS instead of HTTP, just edit your NGINX configuration.