Forcing Elastic Beanstalk Load Balancer from HTTP to HTTPS

This guide is for forcing EBS load balancer to always redirect to https

Bahadir Balban

Started Tech Buzz

@buzzdevelopers47713

Why?

When a user types http:// in the browser instead of https:// it is an insecure connection. Therefore we need to redirect the user to https:// version of the protocol, which creates a secure, encrypted connection. Typically the best setup is to configure the web server for only allowing HTTPS requests, and redirecting any HTTP request to HTTPS.

Steps:

  1. Create file 00_nginx_https_rw.config in .ebsextensions/ folder as below:

files:
  "/tmp/45_nginx_https_rw.sh":
    owner: root
    group: root
    mode: "000644"
    content: |
      #! /bin/bash

      CONFIGURED=`grep -c "return 301 https" /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf`

      if [ $CONFIGURED = 0 ]
        then
          sed -i '/listen 8080;/a \    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }\n' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf
          logger -t nginx_rw "https rewrite rules added"
          exit 0
        else
          logger -t nginx_rw "https rewrite rules already set"
          exit 0
      fi

container_commands:
  00_appdeploy_rewrite_hook:
    command: cp -v /tmp/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/appdeploy/enact
  01_configdeploy_rewrite_hook:
    command: cp -v /tmp/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact
  02_rewrite_hook_perms:
    command: chmod 755 /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh
  03_rewrite_hook_ownership:
    command: chown root:users /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh
  1. Commit the file

  2. Deploy by running eb deploy

What it does:

The part with sed -i ‘/listen 8080’ finds that pattern in the file called

/etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf

It then inserts the http_x_forwarded_proto section in that configuration file. Then logs what it just did. That’s it.

Reference: stack overflow

Forcing NGINX to forward http to https






Join The Discussion