XOR Media

Gunicorn, HTTPS, and Amazon Elastic Load Balancer

If you’re looking to serve both HTTP and HTTPS out of EC2 from python, using gunicorn and ELB you’ll need to add a bit of configuration to get gunicorn to correctly detect which scheme the original request was made with and thus allow Django (or whatever framework you happen to be using) to correctly generate urls with the matching scheme.

ELB doesn’t make use of a standard/common header to pass along the original scheme. It passes the information in X-FORWARDED-PROTO, sending http or https depending on the scheme used for the original request.

Luckily for us gunicorn provides a mechanism for configuring the headers it looks at to decide whether or not the request was secure (https,) secure_scheme_headers. To get it to look for ELB’s signal we need to add the following line to our gunicorn.conf.py file.

secure_scheme_headers = {'X-FORWARDED-PROTO': 'https'}

Once it’s in place we should get back URLs, in the Location header of redirects for example, where the schema matches the request. For more information on the secure_scheme_headers configuration variable search for it in the documentation