2017-04-24 1 views
3

80 및 443 포트에서 실행되는 앱이 있습니다. 사용자가 http 버전 응용 프로그램을 클릭하면 HTTPS로 리디렉션됩니다. 나는 이것을하기 위해 아래 코드를 시도했다. 나는 그것이 https://localhost로 리디렉션해야 로컬 호스트을 치면 HTTP 및 HTTPS 리다이렉션 (노드 및 각도 2 앱)

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

app.use(handleRedirects); 

https.createServer(credentials, app).listen(443, function() { 
    console.log('App is running on port 443'); 
}); 

// all other routes are handled by Angular 
app.get('/*', function(req, res) { 
    console.log("Default handler\n\n\n\n") 
    res.sendFile(path.join(__dirname, '/../../dist/index.html')); 
}); 

app.listen(80, function() { 
    logger.info('App is running on port 80'); 
    admins.refresh(); 
}); 

이 응용 프로그램은 시작 그래서 때. 그러나 예상대로 작동하지 않습니다. 코드에서 무엇이 잘못 되었습니까? 내가 refferred HTTPS redirection for all routes node.js/express - Security concerns

답변

1

아래 코드는 내 문제를 해결했습니다.

var app = express(); 
app.get('/refresh', function (req, res) { 
    res.send(200); 
}); 
https.createServer(credentials, app).listen(443, function() { 
    console.log('App is running on port 443'); 
}); 


var http = express(); 

http.get('/', function (req, res) { 
    res.redirect('https://' + req.get('host') + req.url); 
}) 
http.listen(80, function() { 
    logger.info('App is running on port 80'); 
}); 
1

나는 프로덕션 환경에서만 리디렉션되도록 https를 설정하므로 내 사이트에서 사용하는 코드는 다음과 같습니다.

module.exports.httpsRedirect = function(req,res,next){ 
if(req.headers['x-forwarded-proto'] != 'https' && process.env.NODE_ENV === 'production') 
    res.redirect('https://'+req.hostname+req.url) 
else 
    next() /* Continue to other routes if we're not redirecting */ 
};