mod_wsgi and https

August 28, 2013

I had an Apache on one box running a mod_wsgi Django site on port 81, accessed via http.

I had a second box, again running Apache, proxying onto this Django site with ProxyPass and ProxyPassReverse, and this server was doing the https.

We had a problem where the Django site looked fine when accessed via https, but any 302 redirects jumped out of https and tried to access the site via http, which failed.

We solved this by using the following in our wsgi file:

import os, sys
sys.path.append('/path/to/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'

import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
    environ['HTTPS'] = 'on'
    environ['wsgi.url_scheme'] = 'https'
    return _application(environ, start_response)

import dashboardlicence.monitor
dashboardlicence.monitor.start(interval=1.0)

Note that this breaks access to the file via http - we're telling Django that it's running under https.

The bottom two lines of this file refer to a monitor process that will automatically pick up code changes - see http://drumcoder.co.uk/blog/2009/nov/21/apache-mod_wsgi-config/ for more details.