Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect HTTP to HTTPS on Flask+Heroku

When I attempt to redirect incoming traffic to https I get an infinite redirect loop.

@app.route('/checkout/')                                                                                                                                                                                        
def checkout():                                                                                                                                                                                                 
    checkout = "https://myapp.herokuapp.com/checkout/"                                                                                                                                              
    if checkout != request.url:                                                                                                                                                                             
        print checkout, request.url                                                                                                                                                                             
        return redirect(checkout)                                                                                                                                                                               
    return render_template('checkout.html', key=keys['publishable_key']) 

The request.url is never changed to prefix https. I want to use heroku's piggyback ssl to minimize cost.

like image 883
The Internet Avatar asked Feb 27 '13 15:02

The Internet


2 Answers

1) Do "pip install flask-sslify"

(github is here: https://github.com/kennethreitz/flask-sslify)

2) Include the following lines:

from flask_sslify import SSLify
if 'DYNO' in os.environ: # only trigger SSLify if the app is running on Heroku
    sslify = SSLify(app)
like image 119
Ryan Shea Avatar answered Oct 11 '22 09:10

Ryan Shea


On Heroku, SSL (https) is terminated before it reaches your application, so you app never actually sees SSL traffic. To check whether a request was made with https, you instead have to inspect the x-forwarded-proto header. More info here: How to make python on Heroku https only?

UPDATE: For your use, you should just check request.url for "myapp.herokuapp.com/checkout/"; and verify that the header is "https"

like image 30
friism Avatar answered Oct 11 '22 09:10

friism