简体   繁体   中英

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

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.

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();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM