Hugh's Blog

Nginx 配置自签名的 SSL 证书

 

配置自签名的 SSL 证书很简单,做个记录。

生成证书,一行命令就行:

mkdir certs && cd certs
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt
# Output
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:GD
Locality Name (eg, city) []:GZ
Organization Name (eg, company) [Internet Widgits Pty Ltd]:.
Organizational Unit Name (eg, section) []:.
Common Name (e.g. server FQDN or YOUR name) []:your_ip
Email Address []:admin@your_domain.com

参数说明:

  • req: 证书签署请求

  • -x509: 生成自签名证书

  • -nodes: 跳过为证书设置密码的阶段,这样 Nginx 才可以直接打开证书

  • -days 365: 证书有效期为一年

  • -newkey rsa:2048: 生成一个新的私钥,采用的算法是 2048 位的 RSA

  • -keyout: 生成私钥 selfsigned.key

  • -out: 生成证书 selfsigned.crt

修改 Nginx 配置文件,例如:

server {
    listen 443 ssl http2;
    server_name localhost;

    ssl                         on;
    ssl_certificate             /etc/nginx/certs/selfsigned.crt;
    ssl_certificate_key         /etc/nginx/certs/selfsigned.key;

    ssl_session_timeout 5m;

    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

server {
    listen 80;
    server_name localhost;

    return 301 https://$host$request_uri;
}

可以测试看下效果,例如使用 Docker 容器:

docker run -d --rm --name nginx-self-ssl -v `pwd`:/etc/nginx/certs -v `pwd`/default.conf:/etc/nginx/conf.d/default.conf -p 80:80 -p 443:443 nginx:alpine

参考

Nginx 容器教程

How To Create a Self-Signed SSL Certificate for Nginx in Ubuntu 16.04