简体   繁体   中英

Redirect http to https express.js

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-domain.com , everything is fine. But if I go to http://my-example-domain.com it does not redirect and nothing shows up.

I also have setup some iptables on my ubuntu server

sudo iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
sudo iptables -A INPUT -i eth0 -p tcp --dport 8443 -j ACCEPT
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443




function requireHTTPS(req, res, next) {
  if (!req.secure) {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
}

// all environments
app.set('port', process.env.PORT || 8443);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(requireHTTPS);  // redirect to https
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
    res.render('index');
})

https.createServer(options, app).listen(8443);

So my question is do I just need to add another iptables rule? Or do I need to configure something in my app?

So based on one answer below, I don't think its a middleware problem, but a port issue. For example: if i go to http://my-example-domain.com , doesn't work. But if I add port 8443, http://my-example-domain.com:8443 , it redirects fine.

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);

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.

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();
    }
});

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);

You can achieve redirection from http to https

if(req.headers["x-forwarded-proto"] == "http") {
 res.redirect(301, "https://" + req.host+req.url);
                next();
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM