0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Sなしアクセス対策時のLet's Encryptの自動更新

Last updated at Posted at 2021-09-02

1. 経緯

Let's Encryptは3か月ごとの証明書の更新が必要なので、cronに仕込んで自動で更新したいものです。しかしhttpからhttpsへのリダイレクト設定をしている場合、証明書更新に必要なポート80がすでに使われているため、更新が失敗してしまいます。

2. 前提

あくまで自動化することを最優先に考えているため、更新中はWebサーバの再起動は必要ですし、ポート80は停止します。
想定しているWebサーバはNginxですが、Apacheでも同様の方法でできます。

3. 方法

1. ポート80と443の設定を別ファイルに書き出しておく

ここではhttpからhttpsへリダイレクト設定のファイルをserver80.conf、SSLを用いたWebサーバの設定をserver443.confとします。大本となる設定ファイル(/etc/nginx/nginx.conf)でconfという拡張子のファイルをincludeしているので、拡張子はconfとしなければなりません。

server80.conf
server {
  listen 80;
  server_name example.com;
  return 301 https://$host$request_uri;
}
server443.conf
server {
  listen 443 ssl http2;
  server_name example.com;
  # その他の設定
}

2. シェルを書く

一連の処理を行うシェルスクリプトを書く。ここではcertbot_renew.shという名前とする。
スクリプト内のパスやコマンドは環境によって異なる可能性があるので、適宜読み替えてください。
エラーはチェックしていません。

certbot_renew.sh
# !/bin/sh
NGINXDIR=/etc/nginx/conf.d
mv ${NGINXDIR}/server80.conf ${NGINXDIR}/server80.conf.bak # 拡張子を変えて読み込まなくさせる
systemctl restart nginx
certbot renew
mv ${NGINXDIR}/server80.conf.bak ${NGINXDIR}/server80.conf # 拡張子を戻して読み込ませる
systemctl restart nginx

3. cronに設定

Webサーバの再起動や証明書の更新はrootでなければできないので、rootのcronに設定してください。
下の例では毎月1日の3:00に更新をしています。

0 3 1 * * /path/to/certbot_renew.sh
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?