【问题标题】:Prevent http traffic, and allow https using Automated Certificate management防止 http 流量,并使用自动证书管理允许 https
【发布时间】:2021-11-18 12:52:42
【问题描述】:

我正在使用 express nodejs 模块来创建应用服务器。该应用程序可通过 https 和 http 访问

我想阻止 http 端点。

我已启用自动证书管理。我的问题是,如果我想使用通过 acm 生成的证书,如何在我的 nodejs 代码中使用密钥和证书。

【问题讨论】:

  • “如何在我的 nodejs 代码中使用密钥和证书”是什么意思?不能直接将 HTTP 请求重定向到 HTTPS 吗?

标签: node.js express ssl heroku https


【解决方案1】:

您可以创建一个 HTTPS 服务器并传递私钥和证书,如下所示:

const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();

const options = {
  key: fs.readFileSync('path/to/key', 'utf8'),
  cert: fs.readFileSync('path/to/cert', 'utf8'),
};

const httpsServer = https.createServer(options, app);
httpsServer.listen(8443);

如果您根本不想响应 HTTP 请求,请不要创建 HTTP 服务器。如果您想将用户转发到 HTTPS,则可以添加如下内容:

const http = require('http');

app.use('*', (req, res, next) => {
    if (!req.secure) {
        const [ host ] = req.headers.host.split(':');
        return res.redirect(`https://${host}:8443${req.url}`);
    }

    return next();
});

const httpServer = http.createServer(app);
httpServer.listen(8000);

或者您可以在反向代理级别处理此问题。例如。对于 Nginx:

server {
  listen 80 default_server;
  server_name _;
  return 301 https://$host$request_uri;
}

}

【讨论】:

    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 2012-12-26
    • 2021-02-05
    • 1970-01-01
    • 2014-09-29
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多