需求
一般我们开发的应用程序,部署的时候使用的是http/ws协议,明文的,不安全。怎样让它安全的通过互联网传输呢?
解决
通过 nginx 在客户端和服务端做一个转发,客户端通过 https/wss 访问,然后和服务端的 http/ws 协议通信。即将一个 http/ws 项目,比方说,地址在 http/ws://localhost:8000, 现在我使用 nginx 将它转发到 http/wss://bkhech.top(申请的域名) 上
nginx配置
SSL 模块安装
查看 nginx 是否安装 http_ssl_module 模块
1. /usr/local/nginx/sbin/nginx -V
如果出现 configure arguments: –with-http_ssl_module, 则已安装,直接跳过。否则执行下一步
2. cd /root/nginx-1.9.2 && ./configure --prefix=/usr/local/nginx --with-http_ssl_module
找到nginx安装目录,并重新执行 configure 命令。使用 make 命令编译(使用make install会重新安装nginx,不要执行),此时当前目录会出现 objs 文件夹。
3. cp ./objs/nginx /usr/local/nginx/sbin/
用新的 nginx 文件覆盖当前的 nginx 文件。
4. /usr/local/nginx/sbin/nginx -V
再次查看安装的模块(configure arguments: –with-http_ssl_module说明ssl模块已安装)
SSL 证书部署
两种方式:
- 使用 openssl 命令,创建自签证书(一般为了保证安全会有一个专门的CA机构签发);(遇到问题,因为是证书是自签发的,使用wss无法访问,使用https 可以在curl 加 --insecure参数解决)
- 使用阿里云为特定域名创建证书;
阿里云数字证书申请
申请好之后(使用 bkhech.top 域名申请的),将证书放在服务器的 /usr/local/nginx/conf/ssl 目录
[root@localhost ssl]# pwd
/usr/local/nginx/conf/ssl
[root@localhost ssl]# ll
总用量 8
-rw-r--r--. 1 root root 1675 10月 21 19:56 server.key
-rw-r--r--. 1 root root 3805 10月 21 19:56 server.pem
conf配置
编辑 /usr/local/nginx/conf/vhosts/default.conf,在原有的配置中加入圈红的配置代码
重启nginx
重启nginx,访问服务进行验证即可。
# 重启
/usr/local/nginx/conf/sbin/nginx -s reload
# 验证
1. curl https://a-resource.top/a-static/my2.html --insecure
hello my static resource-a page2
2. curl https://b-resource.top/b-static/my2.html --insecure
hello my static resource-b page2
3. curl https://api.top/a-api/v7/game/gameSurface/recGame --insecure
{
"flag": 0,
"code": "500",
"message": "网络异常,请稍后再试"
}
4.使用在线websocket测试工具(http://coolaf.com/tool/chattest)
[root@localhost ~]# /root/node_modules/wscat/bin/wscat -c wss://bkhech.top/a-websocket/
Connected (press CTRL+C to quit)
> hello world
< Server received from client: hello world