2016-09-16 109 views
3
表示靜態請求

我需要將所有http請求重定向到https,包括對靜態文件的請求。重定向nodejs向https

我的代碼:

app.use(express.static(__dirname + '/public')); 

app.get('*', function(req, res) { 
    if (!req.secure){ 
      return res.redirect('https://' + config.domain + ":" + config.httpsPort + req.originalUrl); 
     } 
    res.sendFile(__dirname + '/public/index.html');  
}); 

和重定向不工作的靜態文件。如果我改變順序:

app.get(...); 

app.use(...); 

然後我的靜態不工作。如何重定向這些請求?

回答

3
var app = express(); 

app.all('*', function(req, res, next){ 
    console.log('req start: ',req.secure, req.hostname, req.url, app.get('port')); 
    if (req.secure) { 
     return next(); 
    } 

    res.redirect('https://'+req.hostname + ':' + app.get('secPort') + req.url); 
}); 
+0

非常感謝。奇蹟般有效。 –

0

看看Node.js模塊express-sslify。正是這樣做 - 重定向所有HTTP請求以便使用HTTPS。

您可以使用它像:

var express = require('express'); 
var enforce = require('express-sslify'); 

var app = express(); 

// put it as one of the first middlewares, before routes 
app.use(enforce.HTTPS()); 

// handling your static files just like always 
app.use(express.static(__dirname + '/public')); 

// handling requests to root just like always 
app.get('/', function(req, res) { 
    res.send('hello world'); 
}); 

app.listen(3000); 

文檔:https://github.com/florianheinemann/express-sslify

+0

我的服務器上的兩個端口的工作。首先是http,第二個是https。我需要用https端口手動重定向到url)) –

0
function forceHTTPS(req, res, next) { 
    if (!req.secure) { 


     var hostname = req.hostname; 


     var destination = ['https://', hostname,':', app.get('httpsPort'), req.url].join(''); 

     return res.redirect(destination); 
    } 
    next(); 
} 


//For redirecting to https 
app.use(forceHTTPS); 

// For serving static assets 
app.use(express.static(__dirname + directoryToServe)); 

重定向到https來服務於靜態資產之前。

0

此代碼重定向在輕鬆的方式要麼HTTP/HTTPS

res.writeHead(301, { 
    Location: "http" + (req.socket.encrypted ? "s" : "") + "://" + req.headers.host + loc, 
});