簡體   English   中英

Node.js和快速重定向到https不適用於主頁

[英]Nodejs & express redirection to https not working for homepage

我正在使用express在我的vps上提供靜態文件。 我創建了兩個服務器httphttps如下所示:

var httpServer = http.createServer(app);
httpServer.listen(httpPort);

var httpsServer = https.createServer(credentials, app);
httpsServer.listen(httpsPort);

通過使用如下所示的中間件:

app.use(function (req, res, next) { 
    !req.secure 
        ? res.redirect(301, path.join('https://', req.get('Host'), req.url)) 
        : next();
});

我的大部分請求都很好地重定向到了https。 但是,當僅使用沒有ssl的域( http://example.com )和沒有任何子路由(例如http://example.com/contact )加載我的網站時,這不會重定向到https。

編輯

我提供靜態文件(為生產而編譯的angular 4應用程序):

app.use(express.static(path.join(__dirname, distFolder)));

我的路線如下:

app.get('*', (req, res) ={ 
    res.sendFile(path.join(__dirname, distFolder, 'index.html'));
});

您能幫我找出我錯過的內容嗎? 我沒有找到這個確切問題的答案。

謝謝。

我們還可以使用node-rest-client正確地重定向到任何URL。

您可以通過npm install node-rest-client

path.join用於將路徑元素連接在一起,不應用於構造URL。 在您的示例中,重定向URL將缺少前導斜杠之一。

> path.join('https://', 'example.com', '/hello/world')
'https:/example.com/hello/world'

相反,您可以使用url.format ,它將構造一個適當的url。

> url.format({ protocol: 'https:', host: 'example.com', pathname: '/hello/world' })
'https://example.com/hello/world'

您的代碼如下所示:

app.use(function (req, res, next) {
  if (req.secure) return next()

  const target = url.format({
    protocol: 'https:',
    host: req.get('Host'),
    pathname: req.url
  })

  res.redirect(301, target)
})

我終於發現了問題所在:在安全測試之前 ,我正在提供公用文件夾...

所以這是現在的步驟:

// Step 1: Test all incoming requests (from http and https servers).

app.use(function (req, res, next) {
    if (req.secure) 
        return next();

    var target = url.format({ // Thanks Linus for the advice!
        protocol: 'https:',
        host: req.hostname,
        pathname: req.url
    });

    res.redirect(301, target);
});

// Step 2: Serve static files.

app.use(express.static(path.join(__dirname, 'your/dist/folder')));

// Step 3: Build routes (in my case with * because of the SPA).

app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'your/dist/folder', 'index.html'));
});

現在它運行良好!

我建議您嘗試在Web服務器層而不是應用程序層上解決此問題,並通過80和443接收安全請求和非安全請求/流量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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