萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Apache 開啟 SSL 服務教程:從 OpenSSL 生成密鑰對到 HTTPS 部署

前置條件檢查


# 檢查模塊編譯狀態
httpd -l | grep ssl
# 或動態模塊
httpd -M | grep ssl_module

# 缺失則需重新編譯或安裝對應包
# Ubuntu/Debian: a2enmod ssl
# CentOS/RHEL: yum install mod_ssl
# Windows: 安裝 OpenSSL 版本

生成密鑰對與 CSR


# 一步生成無密碼私鑰 + CSR
openssl req -new -nodes -newkey rsa:2048 -keyout private.key -out public.csr \
  -subj "/C=CN/ST=Beijing/L=Beijing/O=MyOrg/OU=IT/CN=www.example.com"

# 參數說明:
# -nodes: 不加密私鑰 (避免啟動需輸入密碼)
# -newkey rsa:2048: 同時生成 2048 位 RSA 私鑰
# -keyout: 私鑰輸出文件
# -out: CSR 輸出文件

證書申請與獲取

免費測試證書 (15 天)

訪問 https://demo.sheca.com/testca/TCert1/tcert.asp 貼入 CSR 內容申請。

生產環境:Let's Encrypt (90 天,自動續期)


# Certbot Apache 插件自動配置
certbot --apache -d www.example.com -d example.com

# 或手動模式
certbot certonly --webroot -w /var/www/html -d www.example.com

配置 Apache SSL 虛擬主機


# httpd.conf 或 extra/httpd-ssl.conf

    ServerName www.example.com
    DocumentRoot /var/www/html
    
    SSLEngine on
    SSLCertificateFile /etc/ssl/crt/public.der    # 或 .crt/.pem
    SSLCertificateKeyFile /etc/ssl/crt/private.key
    # SSLCertificateChainFile /etc/ssl/crt/chain.crt  # 中間證書
    
    # 現代安全配置
    SSLProtocol -all +TLSv1.2 +TLSv1.3
    SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
    SSLHonorCipherOrder on

啟動與驗證


# 配置測試
apachectl configtest
# 或 httpd -t

# 啟動 SSL
apachectl startssl
# 或 systemctl restart httpd

# 驗證端口
netstat -tlnp | grep :443
ss -tlnp | grep :443

完整現代化 SSL 配置模板 (Mozilla Intermediate)


# 適用 Apache 2.4.42+ / OpenSSL 1.1.1+
SSLProtocol             all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite          ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
SSLHonorCipherOrder     off
SSLSessionTickets       off
SSLUseStapling          On
SSLStaplingCache        "shmcb:logs/ssl_stapling(32768)"

# OCSP Stapling 需解析器支持
# Resolver 配置在主上下文

證書格式轉換速查

openssl x509 -in cert.pem -outform der -out cert.deropenssl x509 -in cert.der -inform der -outform pem -out cert.pemopenssl pkcs12 -in cert.pfx -out cert.pem -nodesopenssl pkcs12 -export -in cert.pem -inkey key.pem -out cert.pfxopenssl x509 -in cert.pem -pubkey -noout > pubkey.pem
轉換命令
PEM → DER
DER → PEM
PFX/P12 → PEM (含私鑰)
PEM → PFX
提取公鑰
copyright © 萬盛學電腦網 all rights reserved