I\'m trying to reroute http (80)
to https (443)
in my express app. I\'m using some middle ware to do this. If i go to my https://my-example-
I'm using a similar solution, where I also prepend 'www' because our SSL certificate is not valid without it. Works fine in every browser, but Firefox. Any idea?
http.createServer(function(req, res) {
res.writeHead(301, {
Location: "https://www." + req.headers["host"].replace("www.", "") + req.url
});
res.end();
}).listen(80);
This should work.
app.use(function(req,resp,next){
if (req.headers['x-forwarded-proto'] == 'http') {
return resp.redirect(301, 'https://' + req.headers.host + '/');
} else {
return next();
}
});
You can achieve redirection from http to https
if(req.headers["x-forwarded-proto"] == "http") {
res.redirect(301, "https://" + req.host+req.url);
next();
}
You just need to listen to both http and https in your express app. Then include the middleware to reroute if unsecure. Then add an iptable to reroute 443 => 8443. Done.
var redirectApp = express () ,
redirectServer = http.createServer(redirectApp);
redirectApp.use(function requireHTTPS(req, res, next) {
if (!req.secure) {
return res.redirect('https://' + req.headers.host + req.url);
}
next();
})
redirectServer.listen(8080);
This worked fine for me. First install express-force-ssl. this will force server to use secured connection only
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var forceSsl = require('express-force-ssl');
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('certificates/private.key'),
cert: fs.readFileSync('certificates/certificate.crt'),
ca: fs.readFileSync('certificates/ca_bundle.crt')
};
// API file for interacting with MongoDB
const api = require('./server/routes/api');
// Parsers
app.use(forceSsl);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// API location
app.use('/api', api);
app.get('*', (req, res) => {
//alert(req);
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
http.createServer(app).listen(80)
https.createServer(options, app).listen(443);