nginxでLet’s EncryptのSSL証明書を設定

参考にした記事

[サーバー] Let's EncryptとNginxで、https対応を行う - YoheiM .NET
nginx で ssl 設定をする | dogmap.jp
https://letsencrypt.jp/command/

ざっくり手順

  • certbotのインストール
  • コマンドでSSL証明書の発行
  • nginxの設定ファイルの編集
  • nginxの再起動

手順の補足

certbotとは?

certbot:Let's Encryptの自動化サービス。

certbotのインストール

curl -o:ダウンロードしたデータをファイルに出力する。
$ curl https://dl.eff.org/certbot-auto -o /usr/bin/certbot

chmod 700:所有者のみフルコントロールにする。
$ chmod 700 /usr/bin/certbot

Nginxの設定追加

httpsを有効化する /etc/nginx/sites-available/hogehoge.comの内容

server {
    listen 80;
    listen 443 default ssl;
    ssl on;
    ssl_certificate     /etc/letsencrypt/live/www.hogehoge.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.hogehoge.com/privkey.pem;
    server_name www.hogehoge.com;
    access_log /srv/hogehoge.com/public/log/access.log;
    error_log /srv/hogehoge.com/public/log/error.log;
    location / {
        root   /srv/hogehoge.com/public/vh;
        index  index.html index.php;
    }
}

cerbot-autoコマンドでエラーが発生したら、、、

エラー内容

Challenge failed for domain my.example.com
http-01 challenge for my.example.com
Cleaning up challenges


IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: my.example.com
   Type:   unauthorized
   Detail: Invalid response from
   http://my.example.com/.well-known/acme-challenge/hogehogehoge...
   [xxx.xxx.xxx.xxx]: "<html>\r\n<head><title>404 Not
server {
   Found</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>404
   Not Found</h1></center>\r\n<hr><center>"

   To fix these errors, please make sure that your domain name was
   entered correctly and the DNS A/AAAA record(s) for that domain
   contain(s) the right IP address.

こういうのが出たら、.well-known/acme-challengeにアクセスできていない模様。
vi /etc/nginx/conf.d/default.confにて設定を追加して、nginxを再起動してみる。
default.confはなければ新規作成。
/etc/nginx/nginx.confから読み込むようになっている。

#この部分で読み込んでいる。
    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
# 追加する設定
server {
    listen 80;

    server_name my.example.com;
    #別ディレクトリで認証する。
    location ^~ /.well-known/acme-challenge/ {
        default_type "text/plain";
        root         /usr/share/nginx/html;
    }
}

nginx再起動
systemctl reload nginx

参考:certbot renewでLet’s Encrypt の更新エラーが出たので対応しました - Qiita