Redirects on HTTPS

54 views
Skip to first unread message

Tim Sawyer

unread,
Oct 22, 2009, 7:45:02 AM10/22/09
to django...@googlegroups.com
Hi,

I have a django app that works fine using http. We have a requirement to
serve the entire site using https, which is being done at the proxy level
- so the Apache that my django is running inside (mod_wsgi) doesn't know
about the https.

I have a problem with using HttpResponseRedirect - the redirect is
changing the URL to be http. Everything else about the URL is right.

How do I fix this, and have the redirect go to https?

Thanks,

Tim.

Tom Evans

unread,
Oct 22, 2009, 8:57:13 AM10/22/09
to django...@googlegroups.com

I use middleware to update the request to think it came in over https.
This is an extremely cut down version of what we use, but if _every_
request is SSL it should work fine (not all our requests are SSL, and
not every view requires SSL, so ours is a lot more complex in deciding
whether to monkey patch).

class SSLMiddleware(object):

def process_request(self, request):
# request.is_secure() looks in os.environ to see whether request is SSL
# Unfortunately, once you look in os.environ, you can't change it...
# Therefore, we have to monkey patch that function, we know this is SSL
request.is_secure = lambda: True

Cheers

Tom


Graham Dumpleton

unread,
Oct 22, 2009, 7:57:12 PM10/22/09
to Django users
The easier thing to do and which works for both HTTP and HTTPS is to
have have any front end web server such as nginx which is handling the
actual request set a special header when request came via HTTPS. In
Apache configuration you then use mod_setenvif to set HTTPS variable.

As an example, WebFaction has front end nginx web server which handles
HTTPS. They set a range of headers which include:

X-Forwarded-Proto=https

On the Apache side, you then add directive:

SetEnvIf X-Forwarded-Proto https HTTPS=1

The HTTPS variable is picked up as being special by mod_wsgi and it
will fixup wsgi.url_scheme in WSGI environment and Django then uses
it.

This way you don't need to fiddle anything in the Django stack.

For recent one click installs at WebFaction it will do both nginx and
Apache configuration automatically. If older one click install, you
will need to add the Apache configuration bit plus perhaps load
mod_setenvif.

Graham
Reply all
Reply to author
Forward
0 new messages