Create a Self-Signed SSL Certificate for Nginx

紀錄在 Nginx 安裝自簽的 SSL 憑證.

1# 生成私钥
2openssl genpkey -algorithm RSA -out ca.key -aes256
3
4# 生成自签名 CA 证书
5openssl req -new -x509 -key ca.key -out ca.crt -days 3650
 1# 生成私钥
 2openssl genpkey -algorithm RSA -out registry.key
 3
 4# 生成证书签署请求 (CSR)
 5openssl req -new -key registry.key -out registry.csr
 6
 7# 使用 CA 证书签署请求,生成 Docker registry 证书
 8openssl x509 -req -in registry.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out registry.crt -days 3650
 9
10
11openssl x509 -req -in registry.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out registry.crt -days 3650 -extensions v3_usr -extfile openssl.cnf

使用 openssl 建立自簽憑證

1sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/nginx/certs/nginx-selfsigned.key -out /etc/nginx/certs/nginx-selfsigned.crt
1sudo openssl dhparam -out /etc/nginx/certs/dhparam.pem 2048

生成带有 SANs 的证书

如果你使用 OpenSSL 生成自簽名證書 openssl.cnf,確保包含 SANs,可以通過以下命令實現:

 1[ req ]
 2default_bits       = 2048
 3distinguished_name = lindu
 4req_extensions     = req_ext
 5x509_extensions    = v3_ca
 6
 7default_bits = 2048
 8default_keyfile = registry.key
 9default_md = sha256
10default_days = 365
11distinguished_name = lindu
12req_extensions = req_ext
13x509_extensions = v3_usr
14
15[ lindu ]
16countryName                 = CN
17countryName_default         = CN
18stateOrProvinceName         = Shenzhen
19stateOrProvinceName_default = Shenzhen
20localityName                = Shenzhen
21localityName_default        = Shenzhen
22organizationName            = Lindu
23organizationName_default    = Lindu
24commonName                  = lindu-lab.com
25commonName_max              = 64
26
27[ req_ext ]
28subjectAltName = @alt_names
29
30[ v3_ca ]
31subjectAltName = @alt_names
32
33[ alt_names ]
34DNS.1 = lindu-lab.com
35DNS.2 = reg.lindu-lab.com
36IP.1 = 192.168.2.8
1sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/nginx/certs/nginx-selfsigned-reg.key -out /etc/nginx/certs/nginx-selfsigned-reg.crt -config openssl.cnf

Setting Nginx configuration

1ssl_certificate /etc/nginx/certs/nginx-selfsigned.crt;
2ssl_certificate_key /etc/nginx/certs/nginx-selfsigned.key;
3ssl_dhparam /etc/nginx/certs/dhparam.pem;
 1server {
 2    listen 443 ssl;
 3    server_name _;
 4    index index.html index.php;
 5    access_log /var/log/nginx/access.log main;
 6    error_log /var/log/nginx/error.log error;
 7
 8    location / {
 9      proxy_pass http://backend;
10    }
11
12    location ~ /\.ht {
13        deny  all;
14    }
15}

References

comments powered by Disqus