[Fixed]-Django SSL redirection on Heroku: 'Too many redirects'

12👍

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).

5👍

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

2👍

There is note in the Django documentation for SECURE_SSL_REDIRECT stating that:

If turning this to True causes infinite redirects, it probably means your site is running behind a proxy and can’t tell which requests are secure and which are not. Your proxy likely sets a header to indicate secure requests; you can correct the problem by finding out what that header is and configuring the SECURE_PROXY_SSL_HEADER setting accordingly.

1👍

After trying multiple approaches with this and always getting a “Too Many Redirects” error, I simply decided to do all the redirect from CloudFlare and remove it from my Django App.

Here is the documentation.

Leave a comment