如何启动并运行基本 HTTPS Web 服务器

在系统上安装了 node.js 后,你只需按照以下步骤操作即可运行支持 HTTP 和 HTTPS 的基本 Web 服务器!

第 1 步:构建证书颁发机构

  1. 创建要存储密钥和证书的文件夹:

    mkdir conf

  2. 转到该目录:

    cd conf

  3. 抓取此 ca.cnf 文件以用作配置快捷方式:

    wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/ca.cnf

  4. 使用此配置创建新的证书颁发机构:

    openssl req -new -x509 -days 9999 -config ca.cnf -keyout ca-key.pem -out ca-cert.pem

  5. 既然我们在 ca-key.pemca-cert.pem 中拥有我们的证书权限,那么让我们为服务器生成一个私钥:

    openssl genrsa -out key.pem 4096

  6. 抓取此 server.cnf 文件以用作配置快捷方式:

    wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/server.cnf

  7. 使用此配置生成证书签名请求:

    openssl req -new -config server.cnf -key key.pem -out csr.pem

  8. 签署请求:

    openssl x509 -req -extfile server.cnf -days 999 -passin "pass:password" -in csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem

步骤 2:将证书安装为根证书

  1. 将你的证书复制到根证书的文件夹:

    sudo cp ca-crt.pem /usr/local/share/ca-certificates/ca-crt.pem

  2. 更新 CA 商店:

    sudo update-ca-certificates

第 3 步:启动节点服务器

首先,你要创建一个包含实际服务器代码的 server.js 文件。

Node.js 中 HTTPS 服务器的最小设置如下:

var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

https.createServer(httpsOptions, app).listen(4433);

如果你还想支持 http 请求,则需要进行以下小修改:

var http = require('http');
var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('path/to/server-key.pem'),
    cert: fs.readFileSync('path/to/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);
  1. 转到 server.js 所在的目录:

    cd /path/to

  2. 运行 server.js

    node server.js