XOR Media

Coding, Operations, Etc.

Gunicorn, HTTPS, and Amazon Elastic Load Balancer

Posted on Tue 15 May 2012 by

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

In ops, tagged: python, aws, and elb.

About the Author

Ross McFarland Ross McFarland | | |

Ross is a 17 year veteran of the software industry with experience spanning low-level signal processing, web and mobile user interfaces, high-scale distributed web services, infrastructure, and networking. He has made extensive contributions to open source highlighted by his time as a primary maintainer of Gtk2-Perl and author of requests-futures and python-asynchttp libraries. (more)