Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django on ElasticBeanstalk - HTTP to HTTPS redirects

I needed a way to have my Django ElasticBeanstalk application automatically redirect HTTP requrests to HTTPS. Rick Christianson wrote a post [1] about how to do this by overwriting the wsgi.conf file with one that was slightly modified to support the HTTP to HTTPS redirect.

Building off the shoulders of giants, I wanted to do the same, but not have to keep a copy of the config file in my local source directory. Christianson even points out in his post that if ElasticBeanstalk ever changes it's template for the wsgi.conf file, those updates would not be overwritten and you wouldn't get their benefits. To get around that problem, I used sed to insert the new lines into the wsgi.conf file.

References

  1. http://rickchristianson.wordpress.com/2013/11/02/updating-wsgi-automatically-in-amazon-aws/
  2. http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#customize-containers-format-container_commands
container_commands:
01_http_to_https_redirect:
command:
sed -i '/\<VirtualHost \*:80\>/a RewriteEngine On\nRewriteCond %{HTTP:X-Forwarded-Proto} !https\nRewriteRule \!/robots.txt https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]' /opt/python/ondeck/wsgi.conf
@AlamedaCounty

This comment has been minimized.

Copy link

@AlamedaCounty AlamedaCounty commented Apr 23, 2017

This is the best solution I saw online. Many advise to make changes on apache, but this solution is more elegant.

@ilanll

This comment has been minimized.

Copy link

@ilanll ilanll commented Oct 13, 2017

Great solution and much easier to implement than making changes on apache as advised by other people! It worked perfectly for me.

@gignitchayanun

This comment has been minimized.

Copy link

@gignitchayanun gignitchayanun commented Oct 24, 2017

Thank you. It worked for me

@joer14

This comment has been minimized.

Copy link

@joer14 joer14 commented Nov 15, 2017

I'm not sure if this will work consistently - e.g. if you change environmental variables using the AWS EB console, it will rewrite the wsgi but not run the container command.

See: https://forums.aws.amazon.com/thread.jspa?threadID=163369

Here is a gist from that forum post that has a work around:
https://gist.github.com/djshen-ponddy/0c44a5d835aad7746518d90c360a1297

@michealjroberts

This comment has been minimized.

Copy link

@michealjroberts michealjroberts commented Oct 23, 2019

This doesn't work.

@Mohindharan

This comment has been minimized.

Copy link

@Mohindharan Mohindharan commented Jan 7, 2020

Worked like sweet charm. Changing apache config didn't help . Best solution indeed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment