Reputation: 93
I am using nodejs to handle my server and I have a website on it.
I recently set up SSL and want to redirect http to https but couldn't do it. I tried every approved solution on stackoverflow but none of them are working.
Here is my server app:
const express = require('express');
const app = express();
const https = require('https');
const fetch = require('node-fetch');
const bcrypt = require('bcrypt');
const hogan = require('hogan.js');
const fs = require('fs');
const optionSSL = {
key: fs.readFileSync("./etc/ssl/myssl.pem"),
cert: fs.readFileSync("./etc/ssl/myssl.crt")
};
//app.listen(80, () => console.log("Listening at 80"));
app.use(express.static('public', {
extensions: ['html', 'htm'],
}));
app.use(express.json({limit: '1mb'}));
app.use(express.urlencoded({ extended: false }));
https.createServer(optionSSL, app).listen(443, "mydomain.com");
The things that I tried:
Automatic HTTPS connection/redirect with node.js/express
Redirect nodejs express static request to https
How do you follow an HTTP Redirect in Node.js?
Upvotes: 0
Views: 8226
Reputation: 93
Here is my solution to this issue:
const httpApp = express();
const http = require('http');
httpApp.get("*", function(req, res, next) {
res.redirect("https://" + req.headers.host + req.path);
});
http.createServer(httpApp).listen(80, function() {
console.log("Express TTP server listening on port 80");
});
https.createServer(optionSSL, app).listen(443, function() {
console.log("Express HTTP server listening on port 443" );
});
Thank you @Quentin for giving me idea of listening on two ports.
Upvotes: 1
Reputation: 944256
https.createServer(optionSSL, app).listen(443, "mydomain.com");
You are listening on port 443, which is the HTTPS port.
If you want to redirect from HTTP then you need to listen on the HTTP port (and not attach certificates to it).
The simplest way to do this would be to run a completely different server (dedicated to performing the redirects) on port 80. You could write one in Node.js, or you could just use something off-the-shelf like nginx or lighttpd.
Upvotes: 2