LoginSignup
62
56

More than 3 years have passed since last update.

Let's Encryptを利用してApache 2.4サーバをHTTPS化する

Last updated at Posted at 2017-11-10

はじめに

前回の記事ではApache2.4のHTTPS化する手順をご紹介しましたが、今回は実際に「Let's Encrypt」が発行するSSL証明書を使う方法を紹介します。
また証明書の取得/更新を自動化する手順も併せてご紹介します。

更新履歴

  • 2019.6.19 ディレクトリ名を変更

インストール手順

作業方針

前回までと同様にCentOS7向けの手順となります。
その他のOSにインストールする場合は、公式の「Certbotクライアントのインストール手順」をご覧ください。

Apacheの準備

まずはApache HTTPDサーバを起動し、HTTP通信が可能な状態にしてください。
※初めて証明書を作成する場合はまだSSLが利用できない為、以下のファイルは設置せずにApache HTTPDサーバを起動してください。

  • /etc/httpd/conf.d/rewrite.conf
  • /etc/httpd/conf.d/ssl.conf

Certbotインストール

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

yum -y install certbot

証明書の初回作成

以下のコマンドで証明書を初回作成する事ができます。

certbot certonly --agree-tos --non-interactive -d [ドメイン名] --webroot -w [ドキュメントルートのパス] --email [管理者のメールアドレス]

コマンドの実行が完了したら、ディレクトリ/etc/letsencrypt/live/[ドメイン名]/に証明書が自動保存されます。

# ファイル名 設定ディレクティブ 説明
1 cert.pem SSLCertificateFile サーバ証明書
2 chain.pem SSLCertificateChainFile 中間CA証明書
3 fullchain.pem SSLCertificateFile サーバ証明書+中間CA証明書を結合したもの
4 privkey.pem SSLCertificateKeyFile サーバ証明書の秘密鍵

Apache 2.4設定

まずは以下のコマンドでApache設定ディレクトリにシンボリックリンクします。

cd /etc/httpd/
ln -s /etc/letsencrypt/live live

次に、前回紹介した手順をもとに、設定ファイルを追加していきます。

ssl.conf

/etc/httpd/conf.d/ssl.conf
:
<VirtualHost *:443>
    :
    SSLCertificateKeyFile live/[ドメイン名]/privkey.pem
    SSLCertificateFile live/[ドメイン名]/cert.pem
    SSLCertificateChainFile live/[ドメイン名]/chain.pem
    :
</VirtualHost>

rewrite.conf

/etc/httpd/conf.d/rewrite.conf
<IfModule rewrite_module>
    RewriteEngine On
    LogLevel alert rewrite:trace3
    RewriteCond %{HTTPS} off
    RewriteCond %{REQUEST_URI} !(^/.well-known/)
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</IfModule>

※前回の手順と比べ、/.well-known/パスをリダイレクトしないように変更しています。

証明書の更新設定

Let's Encryptが発行する証明書の有効期限は90日間と短い為、自動で更新されるように設定しましょう。

/etc/letsencrypt/letsencrypt-renew.sh
#!/bin/sh
certbot renew -q --no-self-upgrade --post-hook "systemctl restart httpd.service"

上記のスクリプトに実行権限を付与し、crontabを設定しましょう。

chmod 0700 /etc/letsencrypt/letsencrypt-renew.sh
crontab -e

以下の例では、毎日3時に更新チェックが実行されます。

0 3 * * * /etc/letsencrypt/letsencrypt-renew.sh

おわりに

今回まででCentOS7インスタンスの作成~Webサーバの設定まで一通りご紹介しました。
それでは楽しいコーディングをエンジョイしてください!

関連記事のリンクを以下にまとめています。

62
56
1

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