【问题标题】:Redirect all URLs to secured URLs without www in Node.js在 Node.js 中将所有 URL 重定向到不带 www 的安全 URL
【发布时间】:2019-11-11 18:35:21
【问题描述】:

我正在使用下面的代码将我的所有流量重定向到没有 www 的 https 版本,即我的一个应用程序托管在子域上。它应该适用于以下情况:

以上所有内容都应重定向到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


【解决方案1】:

下面的代码片段检查 URL 是否不安全,它会重定向到 https,并从 url 替换 www。

app.use('*',function(req, res, next){
 if (!req.secure) {
   res.redirect('https://' + req.headers.host.replace(/\/\/www\./, '') + req.url);
 }
 next();
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2017-01-14
    • 1970-01-01
    • 2019-05-14
    • 2015-08-03
    • 1970-01-01
    相关资源
    最近更新 更多