開發、測試、內網環境常需自簽 SSL 憑證。本文記錄從生成 4096 位 RSA 金鑰、移除密碼保護、建立 CSR、自簽 CRT、轉 PFX、至 Nginx 啟用 HTTPS 的完整流程。
openssl genrsa -des3 -out hupohost.key 4096
# 提示輸入 PEM 密碼(建議強密碼)
mv hupohost.key hupohost.key.enc
openssl rsa -in hupohost.key.enc -out hupohost.key
# 輸入步驟 1 設定的密碼,輸出無加密私鑰
rm hupohost.key.enc
注意:無密碼私鑰檔案權限務必設為 600(chmod 600 hupohost.key)。
openssl req -new -key hupohost.key -out hupohost.csr
# 依序填寫:
# Country Name (2 letter code) [XX]: CN
# State or Province Name []: Beijing
# Locality Name []: Beijing
# Organization Name []: MyOrg
# Organizational Unit Name []: IT
# Common Name (FQDN) []: www.example.com # 關鍵:必須匹配訪問域名
# Email Address []: admin@example.com
# A challenge password []: # 留空
# An optional company name []: # 留空
openssl x509 -req -days 3650 -in hupohost.csr -signkey hupohost.key -out hupohost.crt
最終可用檔案:hupohost.key(私鑰)、hupohost.crt(憑證)。
openssl pkcs12 -export -inkey hupohost.key -in hupohost.crt -out hupohost.pfx
server {
listen 443 ssl http2;
server_name www.example.com;
ssl_certificate /usr/local/nginx/conf/ssl/hupohost.crt;
ssl_certificate_key /usr/local/nginx/conf/ssl/hupohost.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH:!aNULL:!eNULL:!LOW:!RC4:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS;
ssl_prefer_server_ciphers on;
# HSTS(可選)
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains' always;
location / {
root /var/www/html;
index index.html;
}
}
# HTTP 80 永久導向 HTTPS
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri;
}
nginx -t
systemctl reload nginx
# 瀏覽器訪問 https://www.example.com 確認綠鎖
.crt 匯入「受信任的根憑證授權單位」。chmod 600 *.key,避免 Nginx 啟動警告 SSL: error:0B080074:x509 certificate routines:...:permission denied。firewall-cmd --add-service=https --permanent && firewall-cmd --reload。