为 Nginx 设置自签名的 SSL

本文简单演示如何为 Nginx 配置自签名证书,启用 HTTPS。

安装 Nginx

1
docker run -it -p 80:80 -p 443:443 --name nginx-alpine-ssl alpine /bin/sh
1
2
echo http://mirrors.ustc.edu.cn/alpine/v3.8/main > /etc/apk/repositories
echo http://mirrors.ustc.edu.cn/alpine/v3.8/community >> /etc/apk/repositories
1
apk update
1
apk add nginx
1
mkdir /run/nginx/
1
nginx
1
curl http://localhost
1
vi /etc/nginx/conf.d/default.conf

编辑

1
root /var/www/localhost/htdocs;

保存以后执行

1
nginx -s reload
1
echo "<h1>Hello world!</h1>" > /var/www/localhost/htdocs/index.html;
1
curl http://localhost

生成自签名证书

安装 openssl

1
apk add openssl
1
openssl req -x509 -nodes -days 365 -subj "/C=CA/ST=QC/O=Company, Inc./CN=mydomain.com" -newkey rsa:2048 -keyout /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

输出:

1
2
3
4
5
Generating a RSA private key
......................................+++++
.................................................................................................................+++++
writing new private key to '/etc/ssl/private/nginx-selfsigned.key'
-----

为 Nginx 配置 SSL

编辑 default.conf

1
vi /etc/nginx/conf.d/default.conf
1
2
3
4
 listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;

验证:

1
nginx -t

重新加载配置

1
nginx -s reload
1
curl https://localhost
1
curl https://localhost --insecure

本文标题:为 Nginx 设置自签名的 SSL

文章作者:Morning Star

发布时间:2020年11月25日 - 12:11

最后更新:2021年04月16日 - 15:04

原始链接:https://www.mls-tech.info/nginx/nginx-setup-self-signed-ssl/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。