title: Docker + Gunicorn + Nginx + Django: redirect non-www to www on AWS Route 53
body: <p>I have a Docker + Gunicorn + Nginx + Django setup on AWS EC2 and Route 53. Right now I want to redirect mydomain.com to www.mydomain.com.</p>
  
  <p>Is it appropriate to do a redirect in a Nginx configuration? Or are there are better solutions. </p>
  
  <p>Here is docker-compose-yml, using gunicorn to start the Django server. </p>
  
  <pre><code>version: '2'  
  services:  
    nginx:
      image: nginx:latest
      container_name: dj_nginx
      ports:
        - "80:8000"
        - "443:443"
      volumes:
        - ./src/my_project/static:/static
        - ./src:/src
        - ./config/nginx:/etc/nginx/conf.d
      depends_on:
        - web
    web:
      build: .
      container_name: dj_web
      command: bash -c "python manage.py makemigrations &amp;&amp; python manage.py migrate &amp;&amp; gunicorn my_project.wsgi -b 0.0.0.0:8000"
      depends_on:
        - db
      volumes:
        - ./src:/src
        - ./apps/django_rapid:/src/my_project/django_rapid
      expose:
        - "8000"
  
    db:
      image: postgres:latest
      container_name: dj_db
  </code></pre>
  
  <p>Here is my Nginx Conf</p>
  
  <pre><code>upstream web {  
    ip_hash;
    server web:8000;
  }
  
  # portal
  server {  
      listen 8000;
  
      location / {
          proxy_pass http://web/;
      }
  
      location /media  {
          alias  /media;  # your Django project  media files - amend as required
      }
  
      location /static {
          alias  /static; # your Django project  static files - amend as required
      }
  
      server_name localhost;
  }
  
  
  # portal (https)                                                                                                   
  server {
      listen 443;
      server_name localhost;
  
      ssl    on;
      ssl_certificate    /etc/nginx/conf.d/mynginx.crt;
      ssl_certificate_key    /etc/nginx/conf.d/mynginx.key;
  
      location /media  {
          alias  /media;  # your Django project  media files - amend as required
      }
  
      location /static {
          alias  /static; # your Django project  static files - amend as required
      }
  
      location / {
          proxy_pass http://web/;
      }
  }
  </code></pre>