使用mkcert + nginx构建本机https测试环境

开发中,我们时常需要使用https测试服务,便于系统上线后在https环境下安全运行提供服务。
通常我们在线上使用https来配置对外https服务。开发中,我们一般使用本机localhost进行调试。现代浏览器对于自签名证书使用时,往往会提示自签名的localhost的https证书不安全,需要做一堆设置。
所幸,我们可以使用mkcert来配置本机https正式,并结合nginx形成和系统发布后一致的环境。
在使用windows10作为开发环境时,搭建步骤如下:

  1. 下载需要的软件

1.1 mkcert

下载地址:https://github.com/FiloSottile/mkcert/releases
为了简单直接下载windows预编译的exe版本即可。

1.2 nginx for windows

下载地址:http://nginx.org/en/download.html

  1. 按照相关软件

nginx for windows 直接解压即可。
mkcert可重命名为mkcert.exe (便于输入方面),拷贝到C:\Windows\System32\中,而后打开CMD命令行执行:
mkcert -install 完成安装。安装过程中会自动创建本地受信任的根证书到系统中。

  1. 生成本地https证书和秘钥

此步骤为了方便后续nginx配置。
在CMD命令行执行:
mkcert localhost 127.0.0.1 ::1 YouHostname
系统会在当前目录中生成证书和密钥两个pem文件

  1. nginx中配置https

4.1 准备证书文件

将刚才生成的量pem文件拷贝到解压的nginx的conf/https/目录下(这里为了便于管理在conf下新建了https文件夹用来放置证书文件)

4.2 修改nginx.conf文件

加入多站单点配置应用: include sites-available/*.conf

4.3 建立站点配置文件

在nginx中的conf/sites-available/下建立自己的站点配置文件*.conf。如这里建立一个本地站点配置文件localhost.conf

4.4 在本地站点配置文件中进行http/https站点配置。

这里给出https站点部分配置示例:

  server {
       listen       443 ssl;
       server_name  localhost 127.0.0.1 ::1 Yourhostname;
  
       ssl_certificate      https\localhost+3.pem;
       ssl_certificate_key  https\localhost+3-key.pem;
       ssl_session_cache    shared:SSL:1m;
       ssl_session_timeout  5m;
       ssl_ciphers  HIGH:!aNULL:!MD5;
       ssl_prefer_server_ciphers  on;
  
       location / {
           root   html;
           index  index.html index.htm;
       }
  }
  1. 测试验证

本机进入nginx目录,使用start nginx启动nginx

使用https://localhost/ 访问nginx,可以看到,chrome中访问正常,且不出现安全警告。

你可能感兴趣的:(使用mkcert + nginx构建本机https测试环境)