Question

I get a redirect loop when using SSL middleware to redirect certain urls to HTTPS. What should I do?

My nginx config is set up to forward requests to gunicorn.

Was it helpful?

Solution

There are a couple of steps here.

First of all, modify the way your middleware checks for SSL:

  def _is_secure(self, request):
    if request.is_secure():
      return True

    if 'HTTP_X_SSL_PROTOCOL' in request.META:
      return True

    return False

Then change your nginx config as follows:

server {
    listen 80;
    listen 443 ssl;

    ...

    location / {

        ...
        proxy_set_header X-SSL-Protocol $ssl_protocol;
        proxy_pass http://localhost:8000/;
    }
}

proxy_set_header will only be passed on if ssl_protocol is not null, i.e., it's a secure connection.

Restart nginx and you're done.

OTHER TIPS

Adding to Tom's answer. If you are behind Heroku or other load balancer, the following might help also.

def _is_secure(self, request):
    if request.is_secure():
      return True

    if 'HTTP_X_SSL_PROTOCOL' in request.META:
      return True

    # check the forwarded request's protocol
    if request.META.get('HTTP_X_FORWARDED_PROTO')=='https':
        return True

    return False
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top