Nginx – How to redirect all HTTP traffic to HTTPS for a Django 1.4 application running on an EC2 with nginx/uWSGI behind ELB with an SSL cert

amazon-elbdjangohttpsnginxuwsgi

I would like to know how to put my entire django site behind HTTPS. If anyone tries to come via HTTP I want that user to be redirected to HTTPS. Currently, firefox is giving me the error "Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

My setup is :

1.One AWS load balancer (ELB) with an SSL cert.ificate The ELB has two listeners:

  • load balancer port 80 (HTTP) pointing to instance port 80 (HTTP)
  • load balancer port 443 (HTTPS) pointing to instance port 80 (HTTP)

2.One EC2 instance behind the ELB running nginx/uWSGI

nginx configuration

server {

        listen 80;
        return 301 https://$host$request_uri;
}

server {

        listen 443 ssl;
        set $home /server/env.example.com;

        client_max_body_size 10m;
        keepalive_timeout 120;


        location / {

               uwsgi_pass uwsgi_main;
               include uwsgi_params;
               uwsgi_param SCRIPT_NAME "";
               uwsgi_param UWSGI_CHDIR $home/project;
               uwsgi_param UWSGI_SCRIPT wsgi;
               uwsgi_param UWSGI_PYHOME $home;
             }
}

uwsgi configuration

# file: /etc/init/uwsgi.conf
description "uWSGI starter"
start on (local-filesystems
and runlevel [2345])
stop on runlevel [016]
respawn
exec /usr/local/sbin/uwsgi \
--uid www-data \
--socket 127.0.0.1:5050 \
--master \
--logto /var/log/uwsgi_main.log \
--logdate \
--optimize 2 \
--processes 8 \
--harakiri 120 \
--vhost \
--no-site \
--post-buffering 262144

3.Django settings file has the following settings specific to SSL/HTTPS

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

Any ideas how to properly setup HTTPS?

Thanks

Best Answer

I believe that from Django 1.4 onwards you can just set SECURE_SSL_REDIRECT = True in your settings.py file