[英]Node Express Server doesn't handle http redirects properly
我正在嘗試使用2個Express服務器的組合來將用戶從http重定向到https,並且還將帶有www的請求重定向到非www,因為cert需要非www。 第一個問題是,用戶訪問https://www.example.com時會得到ERR_CONNECTION_REFUSED。 第二個問題,用戶訪問http://www.example.com時出現DNS錯誤。 用戶只能成功訪問http://example.com (並被重定向)和https://example.com 。 我嘗試了一些解決方案,但Express的許多示例似乎已過時,需要改變哪些內容才能涵蓋上述兩個用例?
// Create Express Server
server = express();
httpServer = express();
// Redirect http to https
httpServer.set('port', 80);
httpServer.get("*", function (req, res, next) {
res.redirect("https://" + req.headers.host + "/" + req.path);
});
http.createServer(httpServer).listen(80);
server.set('trust proxy', true);
// Add server static middleware
server.use( st(options.prod.st) );
server.use(function (req, res, next) {
var str = "www.";
if (req.headers.host.indexOf(str) === 0) {
res.redirect(301, req.protocol + "://" + req.headers.host.slice(str.length) + req.originalUrl);
} else {
next();
}
});
// Fallback to /index.html
server.use(fallback(prodRoot));
// Start Server
https.createServer(creds, server).listen(options.prod.port);
添加www的NS記錄后,大多數問題已解決。 感謝@Fella的建議。 更正的代碼如下。 最后,如果用戶登陸https://www.example.com
我還不得不解決一個問題,我需要添加CORS策略來防止Web應用程序中某些XMLHttpRequests上出現混合內容警告。 我還刪除了從www到非www的重定向,這在修復NS記錄之后是沒有必要的。
// Create Connect Server
server = express();
httpServer = express();
// Redirect http to https
httpServer.get('*', function (req, res, next) {
res.redirect(301, 'https://' + req.headers.host + req.path);
});
http.createServer(httpServer).listen(80);
// Add serve static middleware
server.use( st(options.prod.st) );
// Implement CORS policy
server.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// Fallback to /index.html
server.use(fallback(prodRoot));
// Start Server
https.createServer(creds, server).listen(443);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.