EC2/Nginx構成にLet’s Encryptを使って無料でSSL化する | アントレプログラマー

EC2/Nginx構成にLet’s Encryptを使って無料でSSL化する

AWS

こんにちは、ニキです。

この記事は以下のような方におすすめです。

  • ロードバランサーを使わないEC2/Nginx構成でHTTPS接続したい
  • 無料のSSL証明書を使いたい(Let’s Encryptを使います)

今回は、EC2インスタンスにLet’s EncryptのSSL証明書をインストールし、HTTPS接続します。

ロードバランサーを使わない構成で、Webサーバー(EC2インスタンス)へ無料でHTTPS接続したい場合に、ACMを使わず無料の証明書を使いたいならLet’s Encryptで実現できます。

具体的には、EC2インスタンスにCertbotを使ってLet’s Encrypt SSL証明書をインストールし、Nginxの設定を更新した上でHTTPS接続する方法を解説します。

Takaharu Niki

・Webエンジニア6年目。
・バックエンドを中心に、フロントエンドやDevOps業務も経験。
・現在は、自社サービス企業のテックリードとして従事。

Takaharu Nikiをフォローする

Let’s EncryptをインストールできるCertbotとは?

CertbotはLet’s Encrypt推奨のACMEクライアントです。証明書の取得に使います。

ACME(Automatic Certificate Management Environment): 自動証明書管理環境プロトコルのこと。アクミーと読みます。

Let’s Encrypt では、ほとんどの人にCertbotクライアントをおすすめしています。 Certbot を使えば、証明書が簡単に取得でき、ユーザーの希望に応じてインストール作業も行ってくれるからです。 使用するのが簡単で、多数のオペレーティングシステムで動作し、ドキュメントも充実しています

https://letsencrypt.org/ja/docs/client-options/

Let’s EncryptでEC2/NginxをSSL対応

公式ドキュメントの手順に従って進めていきます。

Certbot Instructions
Tagline

Certbotをインストール

以下のコマンドでCertbotをインストールします。

$ sudo dnf install python3 augeas-libs
$ sudo python3 -m venv /opt/certbot/
$ sudo /opt/certbot/bin/pip install --upgrade pip
$ sudo /opt/certbot/bin/pip install certbot certbot-nginx
$ sudo ln -s /opt/certbot/bin/certbot /usr/bin/certbot

Certbotをインストールする方法はいくつかありますが、以下の記事でpipを使ったインストール方法を紹介しています。

証明書の取得と適用

/etc/nginx/nginx.confにドメインを指定しておきます。

以下の記事を参考に、事前にドメインを登録しておきます。

以下のように/etc/nginx/nginx.confのserver_nameにドメイン名を指定しておくと、証明書と自動的に紐づけることができます。

http {
    server {
        listen       80;
        listen       [::]:80;
        server_name  foo.entreprogrammer.net;
    }
}

以下のコマンドで、Let’s Encryptの証明書を取得すると同時に、Nginxの設定ファイルを自動編集できます。

$ sudo certbot --nginx

証明書の取得のみを行う場合は、以下のコマンドを実行します。

$ sudo certbot certonly --nginx

メールアドレスを入力します。

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel):

同意書に同意するために、Yを入力します。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf . You must
agree in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

EFFのメール購読をしたい場合は、Yを入力します。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o:

HTTPSにしたいドメイン名を選択します。

Nginxの設定ファイルによっては、複数の候補があるかもしれません。

Which names would you like to activate HTTPS for?
We recommend selecting either all domains, or all domains in a VirtualHost/server block.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: foo.entreprogrammer.net
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 1

証明書の作成に成功しました。

証明書と鍵が配置され、Nginx設定ファイルが変更されました。

次のステップとして、証明書の自動更新を促されているので、後で設定します。

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/foo.entreprogrammer.net/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/foo.entreprogrammer.net/privkey.pem
This certificate expires on 2023-12-23.
These files will be updated when the certificate renews.

Deploying certificate
Successfully deployed certificate for foo.entreprogrammer.net to /etc/nginx/nginx.conf
Your existing certificate has been successfully renewed, and the new certificate has been installed.

NEXT STEPS:
- The certificate will need to be renewed before it expires. Certbot can automatically renew the certificate in the background, but you may need to take steps to enable that functionality. See https://certbot.org/renewal-setup for instructions.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/etc/nginx/nginx.confを見ると、更新されていることが分かります。

変更箇所には「# managed by Certbot」のコメントが入ります。

http {
    server {
        server_name  foo.entreprogrammer.net;
        root         /usr/share/nginx/html;

        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/foo.entreprogrammer.net/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/foo.entreprogrammer.net/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    }
    server {
        if ($host = foo.entreprogrammer.net) {
            return 301 https://$host$request_uri;
        } # managed by Certbot

        listen       80;
        listen       [::]:80;
        server_name  foo.entreprogrammer.net;
        return 404; # managed by Certbot
    }
}

この時点で、HTTPS接続できるようになっています。

Let’s EncryptのSSL証明書の自動更新設定

証明書の自動更新をCronでスケジューリングしておきます。

$ echo "0 0,12 * * * root /opt/certbot/bin/python -c 'import random; import time; time.sleep(random.random() * 3600)' && sudo certbot renew -q" | sudo tee -a /etc/crontab > /dev/null

/etc/crontabに設定できているかを確認します。

$ cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

0 0,12 * * * root /opt/certbot/bin/python -c 'import random; import time; time.sleep(random.random() * 3600)' && sudo certbot renew -q

これで証明書が期限切れになる心配はなくなりました。

まとめ

この記事は以下のような方におすすめできるように、執筆しました。

  • ロードバランサーを使わないEC2/Nginx構成でHTTPS接続したい
  • 無料のSSL証明書を使いたい(Let’s Encryptを使います)

nginx実践入門

Nginxの構築と運用に関する幅広い知識を得られます。リアルなユースケースを元にした具体例が豊富に紹介されており、初心者から上級者まで、あらゆるレベルのエンジニアにとって実際の問題解決に役立ちます。

Takaharu Niki

・Webエンジニア6年目。
・バックエンドを中心に、フロントエンドやDevOps業務も経験。
・現在は、自社サービス企業のテックリードとして従事。

Takaharu Nikiをフォローする
AWS
Takaharu Nikiをフォローする
アントレプログラマー
タイトルとURLをコピーしました