萬盛學電腦網

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

Apache 配置 HTTPS 加密訪問:從證書生成到虛擬主機實戰

本文演示在 CentOS/RHEL 環境下,為 Apache 配置基於 OpenSSL 的 HTTPS 加密訪問,涵蓋證書生成、虛擬主機配置、模塊加載與驗證全流程。

環境與前置條件

  • 系統:CentOS/RHEL,Apache(httpd)已安裝
  • 域名:www.downcc.com 解析至 192.168.2.115
  • 安裝 SSL 模塊:yum install -y mod_ssl(自動生成 /etc/httpd/conf.d/ssl.conf)

生成自簽證書

cd /etc/pki/tls/certs
openssl req -utf8 -new -key ../private/localhost.key -x509 -days 3650 -out abc_com.crt
# 交互式填寫:
# Country: CN
# State: 510510
# City: GZ
# Organization: ABC.COM
# OU: Mr.Zhang
# Common Name: www.downcc.com  # 必須與域名一致
# Email: root@abc.com

HTTP 虛擬主機配置(/etc/httpd/conf/httpd.conf)

NameVirtualHost 192.168.2.115:80

    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot /var/www/html
    ServerName www.downcc.com
    ErrorLog logs/dummy-host.example.com-error_log
    CustomLog logs/dummy-host.example.com-access_log common

HTTPS 虛擬主機配置(/etc/httpd/conf.d/ssl.conf)


    DocumentRoot "/var/www/html/www.kuteatest.net"
    ServerName www.downcc.com:443
    ErrorLog logs/ssl_error_log
    TransferLog logs/ssl_access_log
    LogLevel warn

    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW

    SSLCertificateFile /etc/pki/tls/certs/abc_com.crt
    SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

    
        SSLOptions +StdEnvVars
    
    
        SSLOptions +StdEnvVars
    

    SetEnvIf User-Agent ".*MSIE.*" \
        nokeepalive ssl-unclean-shutdown \
        downgrade-1.0 force-response-1.0

    CustomLog logs/ssl_request_log \
        "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

關鍵配置解析

指令說明
SSLEngine on啟用 SSL/TLS 引擎
SSLProtocol all -SSLv2啟用所有協議但禁用不安全的 SSLv2
SSLCipherSuite定義加密套件優先級,排除弱加密
SSLCertificateFile公鑰證書路徑(.crt)
SSLCertificateKeyFile私鑰路徑(.key),權限需 600
SetEnvIf User-Agent MSIE兼容舊版 IE 的 SSL 缺陷

驗證與測試

  1. 重啟服務:service httpd restart
  2. 瀏覽器訪問 https://www.downcc.com,接受自簽證書警告
  3. 點擊鎖圖標查看證書詳情,確認 CN、OU、有效期與生成信息一致
  4. HTTP 訪問正常顯示站點內容,HTTPS 加密傳輸生效

生產環境建議

  • 使用 CA 簽發的受信證書(Let's Encrypt 免費、Certbot 自動化)
  • 啟用 HSTS:Header always set Strict-Transport-Security "max-age=31536000"
  • 配置 OCSP Stapling 提升握手性能
  • 定期檢查 ssl_error_log 排查握手失敗

HTTP 訪問測試結果

HTTPS 訪問測試結果

證書信息驗證

HTTPS 最終效果

copyright © 萬盛學電腦網 all rights reserved