为Express和Nginx配置HTTPS

时间:2017-03-13 11:01:22

标签: javascript node.js ssl nginx https

我正在尝试为https连接配置ExpressJS应用。 Express服务器运行在localhost:8080和安全的localhost:8443。

以下是与https相关的server.js代码:

var app = express();

var https = require('https');

const options = {
    cert: fs.readFileSync('/etc/letsencrypt/live/fire.mydomain.me/fullchain.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/fire.mydomain.me/privkey.pem')
};

app.listen(8080, console.log("Server running"));
https.createServer(options, app).listen(8443, console.log("Secure server running on port 8443"));

这是我的Nginx配置:

server {
    listen 80;
    listen [::]:80;
    server_name fire.mydomain.me;

    location / {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

server {
    listen 443;
    listen [::]:443;
    server_name fire.mydomain.me;
    location / {
        proxy_pass https://localhost:8443;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

我做了什么:

  • 使用针对域fire.mydomain.me的Letsencrypt certonly工具生成SSL证书。
  • 配置nginx。
  • 配置server.js节点应用程序。
  • 在Ufw中为443端口添加TCP规则。

我试过

  • 在server.js中注释not-ssl服务器行以强制连接通过ssl配置:当我尝试访问fire.mydomain.me:443而不是#34时,这会为页面提供服务; https:// fire.mydomain.me"。在这两种情况下,都没有SSL。尝试转到https:// fire.mydomain.me生成此消息"此网站不提供安全连接"在谷歌浏览器中。

  • 我首先按照本教程设置我的ssl节点配置: https://medium.com/@yash.kulshrestha/using-lets-encrypt-with-express-e069c7abe625#.93jgjlgsc

2 个答案:

答案 0 :(得分:24)

您不需要在同一主机上运行的nginx反向代理和Node应用程序之间使用HTTPS。您可以将端口80的HTTP请求和端口443的HTTPS请求代理到Node应用程序中的同一端口 - 在这种情况下为8080 - 在这种情况下您不需要配置TLS证书。

您可以将server.js文件更改为:

var app = express();

app.listen(8080, console.log("Server running"));

并对端口80上的HTTP和端口443上的HTTPS使用proxy_pass http://localhost:8080;的nginx配置。

通常这样做。加密环回接口上的流量不会增加任何安全性,因为要嗅探您需要root访问该框的流量,当您拥有它时,您可以读取证书并解密流量。考虑到https://nodejs.org/en/blog/vulnerability/上的大多数帖子都与OpenSSL相关,可以说在Node中使用SSL会使加密环回接口流量的特殊情况下的安全性降低。有关详细信息,请参阅GitHub上Node项目的this discussion

答案 1 :(得分:9)

感谢@rsp解决方案,这是工作的Nginx配置:

$result = $DBcon->query("SELECT username, email, Phone_number, subcription FROM tbl_users join mergeing on tbl_users.user_id = mergeing.donator_1 where mergeing.donor  = {$_SESSION['userSession']}");
if ($result->num_rows == 0) {
    echo "YOU HAVE NOT YET BEEN CONFIRMED";
}else{
while($row = $result->fetch_array())
{
echo $row['username']; 
}
相关问题