内网使用mkcert签名证书
简介
mkcert 是一个用于生成本地自签名 SSL 证书的开源工具,项目基于 Golang 开发,可跨平台使用,不需要配置,支持多域名以及自动信任 CA。
请注意,自签名的证书只在开发和测试环境中使用,并不适用于生产环境。在生产环境中,你应该使用由受信任的证书颁发机构(CA)签名的证书。
准备工作
局域网内访问 Web 服务的场景,因此开始前需要:
- 服务器:用于提供 Web 服务,安装 nginx 并开启 SSL,系统为 CentOS 7.8。
- PC 端:一台 Win10 电脑,用于测试访问,与服务器处于同一局域网。
下载安装
wget -O mkcert https://github.com/FiloSottile/mkcert/releases/download/v1.4.4/mkcert-v1.4.4-linux-amd64
赋权验证
cp mkcert-v1.4.4-linux-amd64 /usr/local/bin/mkcert
chmod +x /usr/local/bin/mkcert
mkcert -version
生成证书文件
[root@centos-77 ~]# mkcert 192.168.3.77 127.0.0.1 ::1 localhost
Created a new local CA 💥
Note: the local CA is not installed in the system trust store.
Note: the local CA is not installed in the Firefox and/or Chrome/Chromium trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️
Created a new certificate valid for the following names 📜
- "192.168.3.77"
- "127.0.0.1"
- "::1"
- "localhost"
The certificate is at "./192.168.3.77+3.pem" and the key at "./192.168.3.77+3-key.pem" ✅
It will expire on 14 October 2025 🗓
由于服务器上已经装了nginx,命令中可以加入 -cert-file 和 -key-file 参数,将文件直接生成到对应的目录里:
生成证书文件到nginx目录
[root@centos-77 ~]# mkcert -cert-file /etc/nginx/certs/server.crt -key-file /etc/nginx/certs/server.key 192.168.3.77 127.0.0.1 ::1 localhost
Note: the local CA is not installed in the system trust store.
Note: the local CA is not installed in the Firefox and/or Chrome/Chromium trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️
Created a new certificate valid for the following names 📜
- "192.168.3.77"
- "127.0.0.1"
- "::1"
- "localhost"
The certificate is at "/etc/nginx/certs/server.crt" and the key at "/etc/nginx/certs/server.key" ✅
It will expire on 14 October 2025 🗓
配置nginx
mkdir -p /etc/nginx/certs
server {
listen 80;
listen [::]:80;
rewrite ^(.*)$ https://$host$1 permanent;
}
server {
listen 443 ssl;
server_name _;
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
nginx -t
nginx -s reload
mkcert的认证机构安装到服务器上
[root@centos-77 ~]# mkcert -install
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox and/or Chrome/Chromium trust store (requires browser restart)! 🦊
查看CA证书的位置
[root@centos-77 ~]# mkcert -CAROOT
/root/.local/share/mkcert
该目录中有两个文件:rootCA-key.pem
和 rootCA.pem
。将 rootCA.pem
复制到 PC 上,并将其后缀改为 .crt
。
双击 rootCA.crt
,根据提示安装证书,步骤如下:
浏览器访问验证,看到连接已经变为安全: