0
votes

I have a AWS ELB that maps traffic:

  • from port 443 (https) to a EC2 instance on port 3000,
  • from port 80 (http) to the same EC2 instance on port 80.

My goal is to have all traffic over https.

On that instance i have a node server listening on port 3000.

I tried to add a http server listening on port 80 to redirect all traffic but there is some permission problem and i also read that it's not a good practice to run a server using sudo command.

I tried to add a nginx configuration to the instance but it didn't work out.

server {
    listen 80;
    server_name app.elaisian.com;
    location / {
        proxy_pass https://app.sitename.com;
    }
}

Thanks in advance

3

3 Answers

0
votes

From AWS docs, the solution is to use the X-Forwarded-Proto header of the HTTP request:

server {
      listen         80;
      server_name    www.example.org;
      if ($http_x_forwarded_proto != "https") {
          rewrite ^(.*)$ https://$server_name$REQUEST_URI permanent;
      }
}
0
votes

I think you can redirect from http to https with Nginx like

server {
    listen 80;
    listen [::]:80;
    server_name app.elaisian.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
   server_name app.elaisian.com;
    ...
 }

you can refer to this post for more information

0
votes

Another option is to send all traffic to your Node server and do something like this:

server.pre(function (req, res, next) {
    var proto = req.header('X-Forwarded-Proto');
    if (proto === 'http' && req.header('host')) {
        let query = req.getQuery() ? '?' + req.getQuery() : '';
        console.log(`Redirecting ${req.getPath()} to https...`);
        res.redirect(302, 'https://' + req.header('host') + req.getPath() + query, next);
    } else {
        next();
    }
});

This will pre-check every request to see if it came across the ELB as HTTP. If so, it will redirect to HTTPS, preserving the full URL. It assumes you're using Restify or Express. You may need to tweak the function calls based on the HTTP package you're using.