一、阿里云平台购买证书,步骤参见阿里云SSL购买教程。
批注 2019-10-22 095533.png
二、认证成功后下载证书
批注 2019-10-22xxx.png
三、将下载好的证书部署到服务器
根据自己的目录结构部署,本次新建soft目录,在soft目录下新建https文件夹,并将下载的 xxx.key 和 xxx.pem部署到https文件夹下
四、服务端 app.js文件中配置 https、http共存
const express = require("express")
const app = new express()
const net = require('net')
const fs = require("fs")
const https = require("https")
const http = require("http")
app.set("host","127.0.0.1")
//根据自己的目录结构配置文件
const options = {
key:fs.readFileSync("../soft/https/xxx.key","utf8"),
cert:fs.readFileSync("../soft/https/xxx.pem","utf8")
}
var httpsServer = https.createServer(options, app)
var httpServer = http.createServer(app)
const httpsPort = 3001
const httpPort=3002
// 监听https http 端口
httpsServer.listen(httpsPort)
httpServer.listen(httpPort)
// 创建服务器
net.createServer(function(socket){
socket.once('data', function(buf){
// buf 返回格式数组,如果https访问,buf[0]为十六进制
// https数据流的第一位是十六进制 “16” ,转换成十进制就是22
var address = buf[0] === 22 ? httpsPort : httpPort;
//创建指向https或http服务器的链接
var proxy = net.createConnection(address, function() {
proxy.write(buf);
//反向代理的过程,tcp接受的数据交给代理链接,代理链接服务器端返回数据交由socket返回给客户端
socket.pipe(proxy).pipe(socket);
});
proxy.on('error', function(err) {
console.log(err);
});
});
socket.on('error', function(err) {
console.log(err);
});
},app).listen(3000);
// node创建的真实端口,此处设置为3000,3000端口需要在阿里云服务器的安全组中开启才能使用,默认是80端口。
// 浏览器访问: http://xxx.com:3000 https://xxx.xom:3000 ,两种方式都可访问