Force HTTPS in Nginx for Django

I have tried to do this:

  1. Create a file named middleware.py (chmod 775, chown www-data) in the same directory as my settings.py
  2. Paste this in middleware.py: http://djangosnippets.org/snippets/880/
  3. Paste this in my settings.py:

    MIDDLEWARE_CLASSES = ( #...
        'djo.middleware.SSLRedirect',
    )
    
    SSL_ENABLED = True
    SSL_URLS = (
        r'/admin/',
    )
    

I get: Internal Server Error

No errors in the development server shown.

Suggestions?

Answers


Found the problem. I had an infinite loop happening and followed this site to fix it:

http://yuji.wordpress.com/2008/08/15/django-nginx-making-ssl-work-on-django-behind-a-reverse-proxy/#comment-1941

Basically, add this to the nginx server conf setting under the proxy location part of the file:

SECURE_PROXY_SSL_HEADER = (‘HTTP_X_FORWARDED_PROTOCOL’, $scheme)

Then add to your django settings file:

MIDDLEWARE_CLASSES = (...
'djo.middleware.SecureRequiredMiddleware',
)

ROOT_URLCONF = 'djo.urls'

HTTPS_SUPPORT = True
SECURE_REQUIRED_PATHS = (
    r'/admin/',

Then create a file in the same django directory called "middleware.py" with the following contents:

from django.http import HttpResponsePermanentRedirect
from django.conf import settings
class SecureRequiredMiddleware(object):
    def __init__(self):
        self.paths = getattr(settings, 'SECURE_REQUIRED_PATHS')
        self.enabled = self.paths and getattr(settings, 'HTTPS_SUPPORT')

    def process_request(self, request):
        if self.enabled and not request.is_secure():
            for path in self.paths:
                if request.get_full_path().startswith(path):
                    request_url = request.build_absolute_uri(request.get_full_path())
                    secure_url = request_url.replace('http://', 'https://')
                    print self.paths, request_url, secure_url
                    return HttpResponsePermanentRedirect(secure_url)
        return None

Voilá! Redirects for any base url desired.


Need Your Help

Bitwise Operations— How to change existing color?

java colors operators bit-manipulation interpolation

I have read up on bitwise operators (& | ^) and I understand that if I were to do:

Background switcher, when a div hits top of the page

javascript jquery css background switch-statement

I've been trying for a while to get this completely working now and perfecting the code, but I am still a rooky javascript programmer so I decided to ask for help.