Reputation: 115
The setup: Domain is purchased at Godaddy and the website is hosted in AWS EC2 Instance in a nodejs environment. (SSL is also purchased for https purpose)
Problem: I have setup SSL using the following code:
var https = require('https');
var http = require('http');
const config = require('./config');
const fs = require('fs');
var app = express();
var redirectApp = express();
var options = {
key: fs.readFileSync(config.sslKeyPath),
cert: fs.readFileSync(config.sslCertPath),
ca: fs.readFileSync(config.sslCaPath)
};
var server = https.createServer(options, app);
var redirectServer = http.createServer(redirectApp);
redirectApp.use(function requireHTTPS(req, res, next) {
if (!req.secure) {
return res.redirect('https://www.domain.com'+ req.url);
}
next();
});
server.listen(httpsport, function() {
console.log("Listening on " + port);
});
redirectServer.listen(httpport, function() {
console.log("Listening on " + port);
});
After deployment, I am able to access https://www.domain.com and https://domain.com but the http://www.domain.com or http://domain.com requests are not getting forwarded to https version. (server error). Please provide a solution to solve this. I tried forwarding the domain to https version in godaddy and it is of no use.
Upvotes: 1
Views: 1877
Reputation: 1734
This will force https on all requests. You may want to put if in front of it to check for an 'dev' or 'production' environment variable.
app.use(function(req, res, next) {
if ((req.get('X-Forwarded-Proto') !== 'https')) {
res.redirect('https://' + req.get('Host') + req.url);
} else
next();
});
Upvotes: 3