Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django SSL redirection on Heroku: 'Too many redirects'

I have a web app deployed to Heroku with a custom domain name which DNS is managed through CloudFlare.

What I want to do is redirect HTTP requests to HTTPS.

After setting SECURE_SSL_REDIRECT to True, according to Django's documentation, I encounter a Too many redirects (or site redirected you too many times) error while accessing the site via the custom domain.

This is what I have in my settings.py file:

SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('X-Forwarded-Proto', 'https')

Note that this redirect works with the myapp.herokuapp.com domain.

I am using DNS + Proxy on CloudFlare, and SECURE_PROXY_SSL_HEADER is set according to Heroku's documentation.

Here is the Heroku log:

2019-04-17T11:21:08.514202+00:00 heroku[router]: at=info method=GET path="/" host=staging.mywebsite.com request_id=cf90ab0c-0895-4faf-aeea-5ee5fe5f970d fwd="115.87.132.194,172.68.242.176" dyno=web.1 connect=0ms service=2ms status=301 bytes=228 protocol=http
like image 868
merc1er Avatar asked Apr 17 '19 11:04

merc1er


Video Answer


2 Answers

Django modifies the format of the header, so "X-Forwarded-Proto" becomes "HTTP_X_FORWARDED_PROTO", so you should replace 'X-Forwarded-Proto' with 'HTTP_X_FORWARDED_PROTO' in your example.

From the Django documentation:

Note that the header needs to be in the format as used by request.META – all caps and likely starting with HTTP_. (Remember, Django automatically adds 'HTTP_' to the start of x-header names before making the header available in request.META.)

There is also an example for this exact header.

Set a tuple with two elements – the name of the header to look for and the required value. For example:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

This tells Django to trust the X-Forwarded-Proto header that comes from our proxy, and any time its value is 'https', then the request is guaranteed to be secure (i.e., it originally came in via HTTPS).

like image 171
jackweath Avatar answered Sep 21 '22 23:09

jackweath


As I understand 'Cloudflare', is that it uses proxies for making your website faster. In combination with heroku it will lead in 'Too many redirects' if the proxy is enabled.

enter image description here

Make sure the cloud in Cloudflare DNS is not set to orange and will not use a proxy before your server.

You can set up SSL in heroku see: https://devcenter.heroku.com/articles/ssl-endpoint

like image 37
S. vanh. Avatar answered Sep 24 '22 23:09

S. vanh.