簡體   English   中英

在Elastic Beanstalk上使用Node / Express重定向到HTTPS

[英]Redirect to HTTPS with Node/Express on Elastic Beanstalk

我正在嘗試讓網站強制HTTPS(從HTTP重定向)。 我們已經通過AWS Elastic Beanstalk設置了HTTPS。 問題是,目前,可以使用HTTP和HTTPS。

閱讀了幾篇文章,包括這篇文章后,下面的代碼就是我想出來的。 不幸的是,這不起作用。

我錯過了什么?

import express from 'express';
import { join } from 'path';

const app = express();
const buildPath = join(`${__dirname}/../build`);
const enforceHTTPS = (req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  else return res.redirect(301, join(`https://${req.hostname}${req.url}`));
};

app.use(express.static(buildPath));
app.use(enforceHTTPS);
app.get('*', (req, res) => res.sendFile(`${buildPath}/index.html`));
app.listen(process.env.PORT || 3000, () => console.log('Server running on port 3000!'));

export default app;

事實證明,我只需要重新排序我的app.use語句 - 提供靜態文件之前調用重定向。

此外,為了使其能夠在IE / Edge上運行,需要將“https://”移動到path.join之外(join刪除第二個正斜杠,盡管所有其他主流瀏覽器都能正確處理它,IE不會'喜歡它)。

這是一個有效的例子:

import express from 'express';
import { join } from 'path';

const app = express();
const buildPath = join(`${__dirname}/../build`);
const enforceHTTPS = (req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') return next();
  return res.redirect(301, `https://${join(req.hostname, req.url)}`);
};

app.use(enforceHTTPS);
app.use(express.static(buildPath));
app.get('*', (req, res) => res.sendFile(`${buildPath}/index.html`));
app.listen(process.env.PORT || 3000, () => console.log('Server running on port 3000!'));

export default app;

代碼中最明顯的問題是HTTPS是從端口443提供的。此外,它看起來像過時的代碼。 為什么不使用最新版本的Express? 如果你看一下HTTPS的例子,他們在這里給出了與你所寫的完全不同的內容: http//expressjs.com/en/api.html搜索'HTTPS'

var express = require('express');
var https = require('https');
var http = require('http');
var app = express();

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

當我過去使用node.js作為代理時,我們獲得不安全的代理連接到安全的方式如下,修改以匹配您的代碼:

const httpsPort = process.env.HTTPS_PORT;

app.use(function(req, res, next) {
    if (req.secure) {
        return next();
    }
    res.redirect(301, ['https://', req.hostname, ':', httpsPort, '/', req.url].join('');
}

其中httpsPort是您的標准https連接將通過的端口。 process.env.HTTPS_PORT將獲取https端口的環境變量(標准為443)。 您可以將其替換為您想要獲取端口的任何內容。

暫無
暫無

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

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