【Azure】ubuntu18.04 でLet'sEncryptでSSL証明を適用


AzureVMのubuntu18.04でLet’sEncryptを使ってSSL設定するまでをまとめました。

前提条件

  1. AzureVMを使ってubuntu18.04を起動して、SSHログインできる。
  2. httpで指定したドメインにアクセスできること
  3. Apache2をインストール済み
$ apache2  -version
Server version: Apache/2.4.29 (Ubuntu)
Server built:   2019-09-16T12:58:48

1. Azureのポート開放

仮想マシンの設定 > ネットワーク からHTTPのポート80番とHTTPSのポート443番を開放する。
追加するときは、受信ポートの規則を追加する から追加できる

2. Let's Encryptで証明書発行

sudo apt install certbot

インストールが終わったらcertbotを実行する
ここではドメイン名をhogehoge.com メールアドレスを[email protected]とする
メールアドレスは入力しなくても良いが、Let’sEncryptから期限切れなどのメールを受信することができるので、入力しといた方が良い。

certbot certonly --webroot --webroot-path /var/www/html/ -d hogehoge.com -m [email protected]

この後に規約に同意するかなどの質問に答える。
基本 "Y" で答えればOK

その後Congratulations!と出れば成功

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at
   /etc/letsencrypt/live/www.hogehoge.com/fullchain.pem. Your cert
   will expire on 2019-12-18. 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"
 - If you lose your account credentials, you can recover through
   e-mails sent to [email protected].
 - 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

証明書が生成されたかを確認するには下記コマンド

$ ls /etc/letsencrypt/live/hogehoge.com/
cert.pem  chain.pem  fullchain.pem  privkey.pem  README

3. Apacheの設定変更

Apacheのssl設定ファイルを編集する

$ vim /etc/apache2/sites-available/default-ssl.conf

vim で設定ファイルを開いたら、下記の該当箇所を変更する。
変更するときは念の為、コピーしてバックアップをとるか、コメントアウトして残しておいたほうが万が一のときに助かる。(設定ミスで、アクセスできなくなった経験あり)

ServerAdmin [email protected] ←変更
DocumentRoot /var/www/html
ServerName hogehoge.com ←変更
SSLCertificateFile      /etc/letsencrypt/live/hogehoge.com/cert.pem ←変更
SSLCertificateKeyFile   /etc/letsencrypt/live/hogehoge.com/privkey.pem ←変更
SSLCertificateChainFile /etc/letsencrypt/live/hogehoge.com/chain.pem ←変更

私の環境ではServer Nameが最初から記述されていなかったため、自分で記述。

その後Apacheを再起動するとHTTPSで接続できるようになる

service apache2 restart

うまくいかないときは

謎のエラーでうまくいかないときは、管理者モードでやるとうまくいきました。

sudo su -

でroot権限で上記手順をやってみてください。

Let’sEncryptは3ヶ月で期限が切れるので、それの自動更新とHTTPSへのリダイレクト設定は次回行います。