【发布时间】:2019-11-11 18:35:21
【问题描述】:
我正在使用下面的代码将我的所有流量重定向到没有 www 的 https 版本,即我的一个应用程序托管在子域上。它应该适用于以下情况:
- http://subdomain.domain.com
- http://www.subdomain.domain.com
- https://www.subdomain.domain.com
- www.subdomain.domain.com
以上所有内容都应重定向到https://subdomain.domain.com。
我正在我的 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);
}
}
});
我无法使重定向工作。对于第四个 URL,即 www.subdomain.domain.com,我也更新了我的 DNS。
【问题讨论】:
-
第四个 URL (
www.subdomain.domain.com) 是什么意思?所有网址都有协议。
标签: node.js express http redirect https