The right way for your WSGI app to know if it's using HTTPS
Suppose that you have a WSGI application that's running under Apache, either directly as a CGI-BIN through some lashup or perhaps through an (old) version of mod_wsgi (such as Django on an Ubuntu 12.04 host, which has mod_wsgi version 3.3). Suppose that you want to know if you're being invoked via a HTTPS URL, either for security purposes or for your own internal reasons (for example, you might need separate page caches for HTTP versus HTTPS requests). What is the correct way to do this?
If you're me, for a long time you do the obvious thing; you look
at the HTTPS
environment variable that your WSGI application
inherits from Apache (or the web server of your choice, if you're
also running things under an alterate).
If it has the value on
or sometimes 1
, you've got a HTTPS
connection; if it doesn't exist or has some other value, you don't.
As I learned recently by reading some mod_wsgi release notes,
this is in practice wrong (and probably wrong even in theory). What
I should be doing is checking wsgi.url_scheme
from the (WSGI)
environment to see if it was "https"
or "http"
. Newer versions
of mod_wsgi explicitly strip the HTTPS
environment variable
and anyways, as the WSGI PEP
makes clear, including a HTTPS
environment variable was always a
'maybe' thing.
(You can argue that mod_wsgi is violating the spirit of the 'should' in the PEP here, but I'm sure it has its reasons for this particular change.)
Not using wsgi.url_scheme
was always kind of conveniently lazy;
I was pretending that WSGI was still basically a CGI-BIN environment
when it's not really. I always should have been preferring wsgi.
environment variables where they were available, and wsgi.url_scheme
has always been there. But I change habits slowly when nothing
smacks me over the nose about them.
(This may have been part of an mod_wsgi issue I ran into at one point, but that's another entry.)
|
|