Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable https on Node-Express App on AWS EC2

I have a node Express app running on an AWS EC2 Instance. I am able to run the server and connect to the express app using http://ec2-xx-xxx-xxx-242.us-west-2.compute.amazonaws.com

But when I use https instead of http, it doesn't work, despite having port 443 open on my instance.

Could some one please suggest how I could enable https on my express app.

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var httpsRedirect = require('express-https-redirect');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

app.get('/hello', (req, res) => res.sendStatus(200));
app.get('/health-check', (req, res) => res.sendStatus(200));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// *** HERE I am setting my App to listen on port 443

//app.listen(8080);
app.listen(8443);

module.exports = app;

Here are the rules on my EC2 Instance, where the port 443 is open for all traffic.

enter image description here

I enabled I forwarding from port 443 to 8443 on my AWS EC2 Linux Instance:

sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443

Opened the Linux firewall to allow connections on port 443:

sudo iptables -A INPUT -p tcp -m tcp --sport 443 -j ACCEPT
sudo iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
like image 782
kurrodu Avatar asked Nov 19 '22 05:11

kurrodu


1 Answers

This is quite easy but require some time for understanding how it usually works. This should be great place to start: https://www.sitepoint.com/configuring-nginx-ssl-node-js/

In few words:

  1. stay your express app as is
  2. generate certificates
  3. install and configure reverse proxy which will handle https. Nginx is great choice.
like image 136
Alex Povar Avatar answered Dec 26 '22 00:12

Alex Povar