EC2 Ubuntu NGINX config HTTPS Redirect giving me error: ERR_TOO_MANY_REDIRECTS

Viewed 760

Background

I've got an Ubuntu machine running on an AWS EC2 instance (Node/Express app), with its SSL certs setup using Certificate Manager and a Load Balancer. This worked fine for going to my site directly using https, e.g, https://example.com. However, using http, resulted in an insecure connection.

Checking on whynopadlock.com, I'm told my web server is not forcing HTTPS. My web server is setup using NGINX as a reverse proxy to my private IP of my EC2 instance. I've hunted around and can't quite seem to find a proper example like mine, although I've tried to piece together what I was able to find.

When I attempt to setup a force HTTPS redirect, I get ERR_TOO_MANY_REDIRECTS.

Before: Original Nginx Config

server {
    listen 80;
    location / {
        proxy_pass http://{{MASKED_EC2_INSTANCE_PRIVATE_IP_FOR_POST}}:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Notes: This config allowed https://example.com to load fine, however there was no redirect if navigating to the site using http://example.com and resulted an insecure connection.

After: NGINX Config after adding HTTPS Redirect

# HTTP
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    return 301   https://$host$request_uri;
}

# HTTPS
server {
    listen       443 default_server;
    listen       [::]:443 default_server;
    server_name  localhost;

    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass https://{{MASKED_EC2_INSTANCE_PRIVATE_IP_FOR_POST}}:8000;
        proxy_set_header X-Forwarded-Proto https;
    }
}

Issue

I see now that when I load the domain with http, I am redirected successfully to https, however I am receiving the error ERR_TOO_MANY_REDIRECTS.

Can anyone help me understand what I'm missing or may be doing wrong in my config?

1 Answers

Since you are using ALB, you can redirect http to https on the ALB itself. AWS provides a guide how to set it up:

How can I redirect HTTP requests to HTTPS using an Application Load Balancer?

The process involves creating http listener and adding redirection action to it instead of regular forward rule. This way you don't have to perform any changes to your instances, as all is taken care of by the ALB.

Also since you are using AWS Certificate Manager you have to use ALB as ACM SSL cert can't be used on instance. The ACM can only be used on a load balancer (ALB, CLB or NLB), CloudFront distro or API Gateway.

Related