Jesse James
Jesse James

Reputation: 1223

HTTPS Server in Node.js

I was wondering how can I create a https server in node listening on Port 443 in a way that when I type :

https://my.ip.address:443 it should work.
https://my.ip.address it should work.
my.ip.address (without the https://) it should work and redirect me to https)
my.ip.address:443 it should work and redirect me to https

So far I was only able to make the first and second url work.

So my question is how can I make it also work for the other two possibilities (the final two). Thanks

Upvotes: 0

Views: 392

Answers (2)

vodolaz095
vodolaz095

Reputation: 6986

You can make redirects from http to https. Via nginx

https://github.com/vodolaz095/hunt/blob/master/examples/serverConfigsExamples/nginx.conf#L22-L39

  server {
    listen       80;
    server_name  example.org;
    rewrite      ^ https://$host$request_uri? permanent;
  }

Via expressjs middleware

https://github.com/vodolaz095/hunt/blob/master/examples/index.js#L133-L139

something like this:

app.use(function (request, response, next) {
  if (request.protocol === 'http') {
    response.redirect('https://yourhostname.com' + request.originalUrl);
  } else {
    next();
  }
});

Upvotes: 1

Quentin
Quentin

Reputation: 943108

If you type my.ip.address into a browser's address bar then it will request http://my.ip.address:80. To get that to work with your SSL version you need to:

  1. Listen for HTTP (not HTTPS) on port 80
  2. Issue a 301 HTTP Redirect to the SSL site

If you type my.ip.address:443 into a browser, then it will request http://my.ip.address:443. This will try to make an HTTP request without setting up SSL first and get an error. There is nothing you can do about that.

Upvotes: 3

Related Questions