Reputation: 57
I have a flask app running on an EC2 instance, this sits behind a an AWS ELB which terminates SSL. The ELB then forwards the connection to the instance on port 80.
I'm trying to force flask to redirect all http requests to https. I've tried SSLify and the following, the problem is that when I use the following I receive to many redirects error. I believe this is because the ELB is forwarding to the instance on 80 and then the redirect sends it back to the ELB creating an infinite loop. SSLify doesn't seem to work as the instance isn't the SSL termination point.
Looks like I need to implement request.is_secure to make this work and respect X-Forwarded-Protocol but I'm not sure how.
@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)
Upvotes: 1
Views: 348
Reputation: 815
Ideally, you should be performing HTTP -> HTTPS redirects on the Load Balancer, not inside flask itself.
See: Redirecting EC2 Elastic Load Balancer from HTTP to HTTPS
Upvotes: 0
Reputation: 57
Implementing proxyfix has resolved the issue.
from werkzeug.contrib.fixers import ProxyFix
sslify = SSLify(app, subdomains=True, permanent=True)
app.wsgi_app = ProxyFix(app.wsgi_app)
Upvotes: 2