Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 使用 OpenSSL 自簽 SSL 憑證完整教學:4096 位金鑰、去密碼、Nginx 配置實戰

編輯:Linux 教學

開發、測試、內網環境常需自簽 SSL 憑證。本文記錄從生成 4096 位 RSA 金鑰、移除密碼保護、建立 CSR、自簽 CRT、轉 PFX、至 Nginx 啟用 HTTPS 的完整流程。

步驟 1:生成 4096 位 RSA 私鑰(帶密碼)


openssl genrsa -des3 -out hupohost.key 4096
# 提示輸入 PEM 密碼(建議強密碼)

步驟 2:移除私鑰密碼(Nginx reload 不需手動輸入)


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)。

步驟 3:生成 CSR(憑證簽名請求)


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 []:             # 留空

步驟 4:自簽生成 CRT(有效期 10 年)


openssl x509 -req -days 3650 -in hupohost.csr -signkey hupohost.key -out hupohost.crt

最終可用檔案:hupohost.key(私鑰)、hupohost.crt(憑證)。

步驟 5:(可選) 轉換為 PFX 供 Windows/IIS 使用


openssl pkcs12 -export -inkey hupohost.key -in hupohost.crt -out hupohost.pfx

步驟 6:Nginx 配置啟用 HTTPS


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 確認綠鎖

常見坑點提醒

  • Common Name (CN) 必須等於訪問域名,否則瀏覽器報「憑證域名不匹配」。
  • 自簽憑證不被系統信任,瀏覽器會警告;開發機可將 .crt 匯入「受信任的根憑證授權單位」。
  • 私鑰檔權限:chmod 600 *.key,避免 Nginx 啟動警告 SSL: error:0B080074:x509 certificate routines:...:permission denied。
  • 防火牆放行 443:firewall-cmd --add-service=https --permanent && firewall-cmd --reload。
Copyright © Windows教程網 All Rights Reserved