為Apache2配置SSL證書並使用重寫模組強制https訪問
阿新 • • 發佈:2022-03-27
配置SSL證書
證書籤發機構會根據你所選的服務端型別響應對應的SSL證書檔案, 對於Apache2, 證書檔案如下
root_bundle.crt 證書檔案
example.com.crt 證書檔案
example.com.key 私鑰檔案
example.com.csr CSR檔案
其中前三個是需要配置的檔案, CSR檔案無需關注.
將前三個檔案放入/etc/apache2/ssl/
資料夾中, 若無此資料夾, 可自行建立.
配置Apache2
首先開啟SSL功能
a2enmod ssl
隨後修改配置檔案/etc/apache2/sites-available/default-ssl.conf
為如下內容
<VirtualHost 0.0.0.0:443> DocumentRoot "/var/www/html" #填寫證書名稱 ServerName example.com #啟用 SSL 功能 SSLEngine on #證書檔案的路徑 SSLCertificateFile /etc/apache2/ssl/example.com.crt #私鑰檔案的路徑 SSLCertificateKeyFile /etc/apache2/ssl/example.com.key #證書鏈檔案的路徑 SSLCertificateChainFile /etc/apache2/ssl/root_bundle.crt </VirtualHost>
再為配置檔案建立軟連結使之生效
a2ensite default-ssl
隨後在配置檔案/etc/apache2/ports.conf
中新增以下欄位
<IfModule ssl_module>
Listen 443
</IfModule>
使之監聽https的443埠.
在使配置檔案生效前檢測配置檔案語法是否正確
apache2ctl configtest
若輸出
Syntax OK
則執行
systemctl reload apache2
過載配置檔案.
此時可以訪問https://example.com, 會發現連結安全, https已啟用, 但此時若直接訪問域名, 仍然走的是http協議, 接下來解決這個問題.
使用Apache2的重寫模組強制https訪問
在配置檔案/etc/apache2/sites-available/000-default.conf
中的<VirtualHost *:80>
域內新增如下欄位
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
然後開啟重寫模組
a2enmod rewrite
然後驗證一下配置檔案有無語法錯誤, 若驗證通過過載配置檔案
systemctl reload apache2
至此配置完成, 在瀏覽器直接輸入域名則自動重定向至https協議.