Amazon LinuxのApacheサーバをLet's Encryptを使ってhttps化

AWSのEC2インスタンスにてhttps化するにはELBが必要となってしまう。なんとか無料でできないものかと探したところ、Let's Encryptなるものを見つけた。

letsencrypt.jp

Let's Encrypt は、認証局(CA)として「SSL/TLSサーバ証明書」を無料で発行するとともに、証明書の発行・インストール・更新のプロセスを自動化することにより、TLSHTTPSTLSプロトコルによって提供されるセキュアな接続の上でのHTTP通信)を普及させることを目的としているプロジェクトです。

早速インストール&設定する。Amazon Linuxでは使えない、や警告が出るなどの記事があったが結果的に問題なかった。

設定は以下のサイトを参考にした。備忘録として作業ログを残す。

qiita.com

ツールを使用したSSL設定

設定用のツールが用意されているので取得する。

curl https://dl.eff.org/certbot-auto -o /usr/bin/certbot-auto

権限変更。

chmod 700 /usr/bin/certbot-auto

証明書を作成する。

certbot-auto certonly --webroot -w [ドキュメントルート] -d [ドメイン名] --email [登録用メールアドレス] -n --agree-tos --debug

以下の様な通知が出る。2019-03-01に期限切れになるので証明書の再取得が必要。あとでcronで定期更新できる様にする。

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/[ドメイン名]/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/[ドメイン名]/privkey.pem
   Your cert will expire on 2019-03-01. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot-auto
   again. To non-interactively renew *all* of your certificates, run
   "certbot-auto renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

mod_sslをインストール。

yum install mod24_ssl

作成されたssl.confを編集する。

vim /etc/httpd/conf.d/ssl.conf

//cert.pemまでのパスを記載
SSLCertificateFile /etc/letsencrypt/live/[ドメイン名]/cert.pem
//privkey.pemまでのパスを記載
SSLCertificateKeyFile /etc/letsencrypt/live/[ドメイン名]/privkey.pem
//コメントアウトを削除し、chain.pemまでのパスを記載
SSLCertificateChainFile /etc/letsencrypt/live/[ドメイン名]/chain.pem

apacheを再起動。

service httpd restart

https://[ドメイン名]/でアクセスしてapacheのテスト画面が出たら成功 もし、httpsでアクセスできないときは、EC2のセキュリティグループに、port: 443を許可するインバウンドルールを追加する。

証明書を定期更新

このままだと一定期間後に期限切れになってしまうので、cronで定期的に更新する様にしてあげる。

00 01 * * * root /usr/bin/certbot-auto renew --post-hook "service httpd restart"

httpをhttpsへリダイレクトする

もともとhttpコンテンツがあった場合は、httpでアクセスされたらhttpsへ転送する様に設定する。 ssl.confにhttp接続された際の転送設定を追加する。

vim /etc/httpd/conf.d/ssl.conf

<VirtualHost *:443>
# 〜中略〜
</VirtualHost>
# 以下を追加する
# example.comを適宜変更
<VirtualHost *:80>
  ServerName example.com:80
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^example\.com
  RewriteRule ^/(.*)$ https://example.com/$1 [R=301,L]
</VirtualHost>

設定したらapacheを再起動して反映。

service httpd restart

httpでアクセスして、httpsに転送されれば成功。