[英]Redirect all URLs to secured URLs without www in Node.js
I am using the code below to redirect all my traffic to https version without www ie for one my application hosted on a subdomain. 我正在使用下面的代码将所有流量重定向到不带www的https版本,例如,我的应用程序托管在一个子域中。 It should work for the following cases:
它适用于以下情况:
All the above should redirect to https://subdomain.domain.com . 以上所有内容均应重定向到https://subdomain.domain.com 。
I am trying out this on my Node.js application. 我正在我的Node.js应用程序上尝试此操作。
app.use('*', function(req, res, next) {
// https
if (req.headers["x-forwarded-proto"] == "https") {
// https with www
if (req.headers.host.match(/^www/) !== null) {
res.redirect(301, 'https://' + req.headers.host.replace(/^www\./, '') + req.url);
}
// https without www
else {
next();
}
}
// http
else {
// http with www
if (req.headers.host.match(/^www/) !== null) {
res.redirect(301, 'https://' + req.headers.host.replace(/^www\./, '') + req.url);
}
// http without www
else {
res.redirect("https://subdomain.domain.com" + req.url);
}
}
});
I am not able to get the redirection working. 我无法使重定向工作。 For the fourth URL ie www.subdomain.domain.com, I have updated my DNS as well.
对于第四个URL,即www.subdomain.domain.com,我也更新了DNS。
Below Code Snippet Check if URL is not secure it redirects to https with replacing www from url. 在代码段下方,检查URL是否不安全,并通过从URL替换www来重定向到https。
app.use('*',function(req, res, next){
if (!req.secure) {
res.redirect('https://' + req.headers.host.replace(/\/\/www\./, '') + req.url);
}
next();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.