RHEL / CentOS 7 安裝 Apache mod_ssl


以下會記錄在 RHEL 及 CentOS 7 安裝及設定 Apache mod_ssl 的的方法, 以下假設已經使用 YUM 安裝好 Apache, 並會示範安裝自簽憑證及 CA 發行感證的步驟。

首先用 YUM 安裝 mod_ssl:

# yum install mod_ssl

安裝好 mod_ssl 後, 系統會自動建立 Apache 的 ssl 設定檔, 位置在 /etc/httpd/conf.d/ssl.conf, 但在修改 ssl.conf 前, 先建立好儲存憑證的目錄, 及產生憑證:

建立儲存憑證的目錄, 以下設定在 /etc/httpd/ssl

# mkdir /etc/httpd/ssl

然後用 openssl 建立 priviate key 及 憑證:

# cd /etc/httpd/ssl
# openssl req -nodes -newkey rsa:2048 -keyout myserver.key -out server.csr

輸入上面指令後, 會要求輸入國家, 城市, 機構名稱及 hostname 等資訊, 然後用 openssl 建立 ca.crt 檔案:

# openssl x509 -req -days 365 -in server.csr -signkey myserver.key -out ca.crt

現在可以編輯 ssl.conf:

# vi /etc/httpd/conf.d/ssl.conf

找到 “DocumentRoot”, 將前面的 “#” 注解刪除, 並設定成網頁的目錄, 預設是 /var/www/html; 然後將 ServerName 的注解刪除, 並改成 Domain Name, 改成類似這樣:

DocumentRoot “/var/www/html”
ServerName www.yourdomain.com

上面的設定跟 http 的設定差不多, 現在是設定 SSL 的部份, 找到以下兩行:

SSLCertificateFile
SSLCertificateKeyFile

將以上兩個參數前的注解刪除, 並指定到上面建立的 private key 及自簽憑證:

SSLCertificateFile /etc/httpd/ssl/ca.crt
SSLCertificateKeyFile /etc/httpd/ssl/myserver.key

因為使用 SSLv3 或以下有安全問題, 需要關閉 SSLv3, 找到以下一行:

SSLProtocol all -SSLv2

改為:

SSLProtocol all -SSLv2 -SSLv3

儲存檔案後離開, 並重新啟動 Apache:

# systemctl restart apache

要測試是否成功安裝, 可以打開瀏覽器, 開啟伺服器的 https:// 頁面, 例如:

https://www.yourdomain.com/

由於上面只是使用自簽憑證, 瀏覽器不能驗證憑證, 所以瀏覽器會發出警告憑證不可信, 只要選擇繼續瀏覽, 便可以看到加密了的網頁。

如果不想出現上面的憑證不可信警告, 可以向在網路向各大 CA 購買 SSL 憑證, 然後將憑證儲存到伺服器, 並修改 ssl.conf 便可以了。

如果要將所有 http:// 的頁面轉到 https:// 的話, 可以開啟 httpd.conf, 在 http:// 的 VirtualHost 段落內, 加入以下一行:

Redirect permanent / https://www.yourdomain.com

儲存後重新新動 Apache, 這樣便會將所有 http:// 的請求轉到 https://www.yourdomain.com

Leave a Reply