Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

 I've got a Node.js powered site that I'm running on Amazon Elastic Beanstalk.

My Node.js app listens on port 8080, and I'm using the nginx elastic load balancer configuration with my EB app, listening on port 80 and 443 for HTTP and HTTPS.

However, I only want to accept traffic in my app that has come via HTTPS.

I could rig something up in the app to deal with this, but am interested in a way to get the load balancer to redirect all HTTP requests to my site via HTTPS. 

1 Answer

0 votes
by (44.4k points)

Configure your environment so that it can respond to both the ports 80 and 443. Then create .ebextensions folder inside your main node.js application folder. Create a file inside called 00_nginx_https_rw.config, and the content inside looks like:

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

This configuration will create a deployment hook which makes the changes inside /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf by adding rewrite rules.

If you want to undo this later, use the below scripts to do so:

/opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh

/opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer

Browse Categories

...