EC2+Nginx+node.jsのWEBサーバーをLet’sEncryptでSSL化する

この手順で構築したWEBサーバーを使用する。

・ ディストリビューション: Amazon Linux 2023.1.20230825
・ インスタンスタイプ: t3a.nano
・ ボリュームサイズ: 20GB

python3の仮想環境を使用してcertbotをインストールする。
※この手順作成時はpython3.9だった

# dnf install pip
# mkdir /opt/certbot
# python3 -m venv /opt/certbot
# /opt/certbot/bin/pip install --upgrade pip
# /opt/certbot/bin/pip install certbot

ACMEチャレンジのための設定を追加する。

server {
    listen       80;
    listen       [::]:80;
    server_name  _;
    location = /.well-known/acme-challenge/ {
        root /usr/share/nginx/html/.well-known/acme-challenge/;
    }
}

証明書を取得する。
※何度も失敗すると制限がかかるので予め--dry-runオプションを指定してテストした方が良い

/opt/certbot/bin/certbot certonly --webroot -w /usr/share/nginx/html/ -d testapp.example.com

Nginxの設定ファイルを変更する。

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name testapp.example.com;
    ssl_certificate     /etc/letsencrypt/live/testapp.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/testapp.example.com/privkey.pem;
    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_path http://localhost:3000/;
    }
}

Nginxの設定をリロードしてhttpsでの接続を確認する。

# systemctl reload nginx

cronに証明書を更新するジョブを追加する。

0 4 * * * /opt/certbot/bin/certbot renew --deploy-hook "systemctl reload nginx"
カテゴリーAWS