You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搭建Node.js http-proxy代理服务器所需SSL证书及生成方法咨询

Node.js http-proxy代理服务器的SSL证书方案与生成步骤

需要的SSL证书类型

你需要自签名CA(证书颁发机构)证书,以及由该CA签名的代理服务器证书。因为要代理任意HTTPS网站,代理服务器需扮演中间人角色:解密Firefox的请求,重新加密后转发到目标网站。只有让Firefox信任你的CA证书,才不会触发“证书不安全”的提示。

证书生成步骤(使用OpenSSL)

所有命令在终端执行:

  1. 生成CA私钥(务必妥善保管,避免泄露)
openssl genrsa -out ca.key 2048
  1. 生成自签名CA证书(有效期设为10年,可按需调整)
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt

执行时会提示填写信息,仅Common Name需填写(比如My Proxy CA),其他字段直接回车留空即可。

  1. 生成代理服务器的私钥
openssl genrsa -out proxy.key 2048
  1. 生成代理服务器的证书签名请求(CSR)
openssl req -new -key proxy.key -out proxy.csr

这里的Common Name建议填写代理服务器的域名或IP(本地测试填localhost即可),其他字段可留空。

  1. 用CA证书签名代理服务器的证书
openssl x509 -req -in proxy.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out proxy.crt -days 365 -sha256

让Firefox信任CA证书

  1. 打开Firefox,进入设置 -> 隐私与安全 -> 证书 -> 查看证书 -> 证书机构
  2. 点击导入,选择生成的ca.crt文件
  3. 在弹窗中勾选信任该CA来标识网站,确认保存

http-proxy配置示例

以下是实现中间人代理的核心代码:

const http = require('http');
const httpProxy = require('http-proxy');
const fs = require('fs');

// 加载证书文件
const sslOptions = {
  key: fs.readFileSync('proxy.key', 'utf8'),
  cert: fs.readFileSync('proxy.crt', 'utf8'),
  ca: fs.readFileSync('ca.crt', 'utf8'),
  mode: 'intercept' // 开启中间人代理模式
};

// 创建代理服务器实例
const proxy = httpProxy.createProxyServer({});

// 创建HTTP服务器,处理普通HTTP请求与HTTPS的CONNECT隧道请求
const server = http.createServer((req, res) => {
  proxy.web(req, res, { target: `http://${req.headers.host}` });
});

server.on('connect', (req, socket, head) => {
  const [host, port] = req.url.split(':');
  proxy.ws(req, socket, head, {
    target: `wss://${host}:${port || 443}`,
    ssl: sslOptions
  });
});

// 监听代理端口(示例用8080)
server.listen(8080, () => {
  console.log('Proxy server running on http://localhost:8080');
});

注意事项

  • 自签名CA证书仅适用于开发/测试场景,禁止用于生产环境
  • 需将Firefox的代理设置指向你的服务器(地址填localhost,端口填8080,或对应部署的IP/端口)
  • 若代理部署在远程机器,生成证书时的Common Name需填写机器的公网IP或域名

内容的提问来源于stack exchange,提问作者Angel Reyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:35:03