0

I have a node server that looks like this:

const express = require("express");
const app = express();
const port = 8000;
const https = require("https");
const fs = require("fs");

const credentials = {
  key: fs.readFileSync("../auth/key.pem"),
  cert: fs.readFileSync("../auth/cert.pem"),
};

const server = https.createServer(credentials, app);
const io = require("socket.io")(server, { cors: { origin: "*" } });

app.get("/", (req, res) => {
  console.log("redirecting http to https");
  if (req.headers.host.match(/^www/) !== null || !req.secure) {
    return res.redirect(
      "https://" + req.headers.host.replace(/^www\./, "") + req.url
    );
  }
});

server.listen(port, () => console.log(`Server is running on port ${port}`));

It should redirect any query from http to https. However, if I go to http://.com/ I get:

<myurl>.com didn’t send any data.
ERR_EMPTY_RESPONSE

I assume this is because in my server, I used https, not http. I can't use http, as I need the server to have an ssl certificate, which requires https. Whatever I end up with, it can only run on one port, so is there any way to implement logic that if a request hits http://.com/ it redirects to https?

Luke Vanzweden
  • 466
  • 3
  • 15
  • You cannot listen for both HTTP and HTTPS on the same port, it's not possible (at least not without writing your own server code from scratch). – President James K. Polk Jun 25 '21 at 01:49
  • Basically you asked how to make nodejs listen for both http and https. The redirect can only be done once you serve both protocols in the first place. – Steffen Ullrich Jun 25 '21 at 03:52

1 Answers1

0

Usual practice to have your express server to stay http and use nginx reverse proxy to handle http to https redirections. Also you most probably care for domain names only in production, so make it work in dev on localhost:someport first, then when you have your server deployed check that your domain resolved to ip address of your vm and specify that domain name in nginx config.