
Ubuntu 20.04でWordPress用のサーバを構築します。HTTPSでアクセス可能にするために、Let's Encriptをインストールしてサーバ証明書をセットアップします。
記事の目次
Let's Encriptをインストールする!
Let's Encriptは、aptコマンドでインストールできます。
# apt install certbot python3-certbot-apache
ApacheのSSL通信を有効にする!
ApacheでSSL通信が可能になるように、SSLの機能を有効化します。HTTPをHTTPSにリダイレクトするため、URLリライトの機能も有効にします。
# a2ensite default-ssl Enabling site default-ssl. To activate the new configuration, you need to run: systemctl reload apache2 # a2enmod ssl Considering dependency setenvif for ssl: Module setenvif already enabled Considering dependency mime for ssl: Module mime already enabled Considering dependency socache_shmcb for ssl: Enabling module socache_shmcb. Enabling module ssl. See /usr/share/doc/apache2/README.Debian.gz on how to configure SSL and create self-signed certificates. To activate the new configuration, you need to run: systemctl restart apache2 # a2enmod rewrite Enabling module rewrite. To activate the new configuration, you need to run: systemctl restart apache2 root@118-27-109-28:/etc/apache2/sites-available
サーバ証明書を配置する!
今回は、Let's Encriptで稼働中のサーバの移行であったため、サーバ証明書を移行します。「/etc/letsencrypt」配下の資源をすべて、tarコマンド等でアーカイブして、そのまま移行します。その他、CA局の証明書は、「/etc/apache2/ssl.crt」ディレクトリを作成して別途移行します。
SSLの設定を行う!
「/etc/apache2/sites-available」ディレクトリの「default-ssl.conf」の設定を変更します。当サイトでは、以下のように設定しています。
SLCertificateFile /etc/letsencrypt/live/lab4ict.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/lab4ict.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/lab4ict.com/chain.pem SSLCACertificateFile /etc/apache2/ssl.crt/ca-lab4ict.pem
その他、DocumentRootや、Aliasの設定をサイトの構成に合わせて行います。
DocumentRoot /var/www/html/wordpress ...
電子証明書を自動更新する!
サーバ証明書の自動更新のため、サーバ証明書を自動更新するコマンドが正常終了するか確認します。
# certbot renew --pre-hook "sudo systemctl stop apache2" --post-hook "sudo systemctl start apache2"
サーバ証明書を自動更新するため、上記で確認したコマンドをcronに登録します。以下は、週1回、月曜日の朝1:00に実行する例になります。
#crontab -e 0 1 * * 1 certbot renew --pre-hook "sudo systemctl stop apache2" --post-hook "sudo systemctl start apache2" # crontab -l
HTTPをHTTPSにリダイレクトする!
HTTPをHTTPSにリダイレクトする設定を行います。
# mkdir /var/www/html/http # cd /etc/apache2/sites-available # vi 000-default.conf ... # DocumentRoot /var/www/html DocumentRoot /var/www/html/http ... RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
.htaccessを有効化する!
「.htaccess」を有効化します。
# cd /etc/apache2 # vi apache2.conf ... <Directory /var/www/> Options Indexes FollowSymLinks # AllowOverride None AllowOverride All Require all granted </Directory> ...
Apacheを再起動する!
設定が一通り終わったところで、Apacheを再起動してサイトアクセスしてみましょう。
# systemctl restart apache2
おわりに
SSL関連の設定は、結構細かいので一気にまとめて行ってみました。