Apache

>

https に対応する

公開日 : 2024/03/03

最終更新日時 : 2024/03/14 10:29:42

環境
CentOS Stream release 9
Apache/2.4.57 (CentOS Stream)
Xserver VPS
EPEL インストール
dnf install epel-release
Snap インストール
dnf --enablerepo=epel install snapd
snapd 起動と自動起動設定
systemctl enable --now snapd.socket
シンボリックリンクを作成
ln -s /var/lib/snapd/snap /snap
core パッケージをインストール
snap install core
certbot コマンドをインストール
snap install --classic certbot
https アクセスさせたいサイトデータが下記パスになっている前提
/var/www/html/newsite
サイトごとの独自 conf 作成
vi /etc/httpd/conf.d/newsite.conf
下記を貼り付ける(キー取得用)
<VirtualHost *:80>
    DocumentRoot /var/www/html/newsite
    ServerName newsite.com

    # for Let's Encrypt
    Alias /.well-known /var/www/html/newsite/.well-known

    <Directory /var/www/html/newsite>
        Require all granted
    </Directory>
</VirtualHost>
キー取得
certbot certonly --webroot -w /var/www/html/newsite -m info@newsite.com -d newsite --agree-tos
各キーが生成されているのを確認
ls /etc/letsencrypt/live/mail.example.com
Output
README  cert.pem  chain.pem  fullchain.pem  privkey.pem
サイトごとの独自 conf の編集
vi /etc/httpd/conf.d/newsite.conf
下記のように書き換える
<VirtualHost *:80>
ServerName newsite.com
ServerAdmin info@newsite.com
DocumentRoot "/var/www/html/newsite"
<Directory "/var/www/html/newsite">
AllowOverride All
Allow from all
</Directory>
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
ErrorLog logs/newsite-error_log
CustomLog logs/newsite-access_log combined
</VirtualHost>
ssl.confの設定
vi /etc/httpd/conf.d/ssl.conf

## SSL Virtual Host Context 以降をすべて削除したうえで

下記を貼り付ける
<VirtualHost *:443>
SSLEngine on
SSLProtocol All -SSLv2 -SSLv3 -TLSv1
ServerName newsite.com
DocumentRoot "/var/www/html/newsite"
SSLCertificateFile /etc/letsencrypt/live/newsite.com/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/newsite.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/newsite.com/chain.pem
<Directory "/var/www/html/newsite">
AllowOverride All
Allow from all
</Directory>
ErrorLog logs/newsite-ssl_error_log
CustomLog logs/newsite-ssl_access_log combined
</VirtualHost>
httpd リスタート
systemctl restart httpd

https でアクセスできれば成功

サイトを増やすごとに同様の処理を行う

証明書の自動更新

証明書の有効期限は3か月となっており期限が来るたびに更新するのは面倒なので自動で更新させる

crontab を開く
crontab -e
下記を貼り付け
0 1 1 * * /usr/bin/certbot renew --cert-name newsit.com --pre-hook "systemctl stop httpd" --post-hook "systemctl start httpd"

:wq Enter で保存 (上記は毎月1日の 1:00 に証明書を更新させる設定)