0

I am using express nodejs module to create the app server. The app is accessibile over both https and http

I want to prevent http endpoint.

I have enabled Automated certificate management. My question is, if I want to use the cert which is generated through acm, how can I use the key and the cert in my nodejs code.

1
  • What does "how can I use the key and the cert in my nodejs code" mean? Can't you just redirect HTTP requests to HTTPS? Commented Sep 25, 2021 at 22:28

1 Answer 1

1

You can create an HTTPS server and pass along a private key and certificate like so:

const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();

const options = {
  key: fs.readFileSync('path/to/key', 'utf8'),
  cert: fs.readFileSync('path/to/cert', 'utf8'),
};

const httpsServer = https.createServer(options, app);
httpsServer.listen(8443);

If you don't want to respond to HTTP requests at all, simply don't create an HTTP server. If you want to to forward users to HTTPS instead, you could add something like this:

const http = require('http');

app.use('*', (req, res, next) => {
    if (!req.secure) {
        const [ host ] = req.headers.host.split(':');
        return res.redirect(`https://${host}:8443${req.url}`);
    }

    return next();
});

const httpServer = http.createServer(app);
httpServer.listen(8000);

Or you can handle this at reverse-proxy level. E.g. for Nginx:

server {
  listen 80 default_server;
  server_name _;
  return 301 https://$host$request_uri;
}

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.