In the last article, I configured an AWS Application Load Balancer to direct both HTTP and HTTPS traffic to an EC2 instance. Although I want my ALB to recieve both HTTP and HTTPS traffic, I want my proxy server (nginx) to only direct requests made via HTTPS to my application server (gunicorn). Put simply, when a user hits my domain using HTTP, they should be redirected to the domain using HTTPS.

Configure nginx to redirect HTTP to HTTPS

Since my proxy server is already receiving requests made via HTTP and HTTPS, I need some way to determine when a request is made with which protocol. Fortunately, AWS Application Load Balancers support the X-Forwarded-Proto HTTP header. This header will forward the protocol with which the client made the request.

Now, we can use this header in the server block of our nginx.conf file to determine if a request was made via HTTP. If it was, we’ll redirect the client to our <domain> via HTTPS.

  if ($http_x_forwarded_proto = 'http') {
    return 301 https://<domain>$request_uri;
  }

Lovely. Now requests made to http://example.com will be redirected to https://example.com.