簡體   English   中英

將所有URL重定向到Node.js中沒有www的安全URL

[英]Redirect all URLs to secured URLs without www in Node.js

我正在使用下面的代碼將所有流量重定向到不帶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是否不安全,並通過從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM