CentOS7にnginxとcertbotを導入してHTTPS環境をさくっと作るの巻

スポンサーリンク
CentOS+nginx+certbot+let's_encrypt

CentOS+nginx+certbot+let’s_encrypt

CentOS7にnginxを導入してSSL対応したい。

今まで何度となくnginxの導入とSSLサーバ証明書の設定を行ってきた。

いやぁ私は通常ネット検索で得られる情報はブログに起こさないんです。不要にネット情報を複製したところでアクセスは来ないし、そもそも意味がないのでね。

で、今回は、ネット検索すればそんなのわかんじゃん!って指摘されそうなことなんだけど、いつも検索してヒットするサイトはバラバラで記載されている内容もまちまちなので、未来の自分の為にここに改めて内容をまとめたいと思ふ。

あと、コピペでの操作を想定して、rootでの操作を意味するプロンプト「#」は記載しません。
CentOS7環境ではsudoコマンドでの操作が一般的と思うので、sudoを先頭につけた記載とします。

作業を行う条件としてこちら

  • CentOS 7.x
  • 80,443番ポートが空いてること
  • SELINUXが無効化or適切に設定されていること
  • 利用するドメインが取得済みであること
  • ドメインがサーバのIPアドレスを向いていること

では、レッツスタート

CentOS7へのnginxの導入

参考にするサイトはこちら
http://nginx.org/en/linux_packages.html#RHEL-CentOS

 

スポンサーリンク

yumリポジトリの追加

ファイルでスコッと、いやサクッとリポジトリ設定ファイルを置ければいいんだけれども、探した限りオフィシャルサイトでリポジトリファイルは公開されていない。なので、仕方がないのでブラウザで開いて見える内容をコピペしてサーバに取り込むこととする。

yumリポジトリファイルは「***.repo」というファイル名で「/etc/yum.repos.d/」配下におくと認識されるので、上記内容を「nginx.repo」というファイル名で作成し設置する。

sudo vi /etc/yum.repos.d/nginx.repo

2020.02.13時点でのリポジトリ設定内容は以下の通り。

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

viコマンドでは、ESC⇒iでインサートモードにして、上記内容を張り付けして、ESC⇒:wq⇒Enterで保存する。
ちなみにwqは「Write」書き込んで「Quit」終了するというコマンド。

認識されているかどうかは、下記「yum repolist」コマンドで確認ができる。

sudo yum repolist

実行結果に「nginx-stable」というリポジトリが表示されていればリポジトリの追加設定は完了です。

 

nginxのインストール

yumリポジトリの設定が完了していれば、下記コマンドでさくっとインストール完了します。

sudo yum -y install nginx

 

nginxの自動起動設定と起動

systemctlコマンドを使ってサービスの有効化、そして同時に起動してみます。
「–now」というオプション、つい最近知りました。enableと同時に起動してくれるオプションです。

sudo systemctl enable --now nginx

本当に起動しているかどうか確認するには、psコマンドでプロセスを確認しましょう。

sudo ps -ef | grep nginx

サービスの自動起動設定は下記コマンドで確認します。

sudo systemctl list-unit-files | grep nginx

はい。nginxの導入まで3秒でできましたね!!

 

CentOS7へのcertbotの導入

次は、certbot(さーとぼっと)の導入を進めていきます。

certbotっていうのは、無料で利用できる Let’s Encrypt が提供する無料のSSLサーバ証明書を管理するのが超絶簡単になるためのものです。

Let’s Encryptが提供する証明書はおよそ90日で有効期限が切れてしまうものなのですが、certbotを用いることで証明書の取得はもちろん、証明書の有効期限が切れる前に自動で更新することもできます。また、今回手順で説明する通りですが、nginxのSSL向け設定を自動で行ってくれる素晴らしい機能も備えています。

参考にするサイトはこちら
https://certbot.eff.org/lets-encrypt/centosrhel7-nginx

epelリポジトリの導入

certbotは CentOS/Red Hat Enterprise Linux向けの高品質なアドオンパッケージを提供しているEPELリポジトリからのインストールになるため、まずは、下記コマンドを実行してEPELリポジトリを導入します。

sudo yum -y install epel-release

yumリポジトリが増えてるかどうかの確認は先ほど行った通りの手順で確認できます。

 

certbotのインストール

epelリポジトリがインストールされている状態であれば、下記コマンドでインストールできます。

今回は、nginxと連携するので、nginx向けの追加機能を提供する「python2-certbot-nginx」もインストールする。

sudo yum -y install certbot python2-certbot-nginx

 

certbotを用いた証明書の取得と設定

certbotの導入でインストールした「python2-certbot-nginx」というやつがものすごいやつで、
なんと、nginxの設定を読み取って、SSL向けの設定を追加してくれるのです。

certbotを用いた証明書の取得を行う際に、自動でnginxの設定がカスタマイズされるようにまずはnginxの初期設定を行っておきます。初期設定といっても、これから取得する証明書に利用するドメインを記載しておくだけです。

 

nginxの設定にドメイン追加

/etc/nginx/conf.d/default.confというファイルを編集してドメイン名を設定しておきます。

vi/vimコマンドで編集してもいいのですが、なるべくコピペで行きたいので、今回は文字列の置換を行う「sed」(せっど)コマンドを使ってみます。
下記の例は、sedコマンドを用いて「localhost」を「example.com」に変更しています。

sudo sed -i 's/localhost/example.com/g' /etc/nginx/conf.d/default.conf

正しく設定が変更されているかは、下記コマンドで確認してください。

sudo grep server_name /etc/nginx/conf.d/default.conf

 

certbot実行

では、準備が整いましたのでcertbotを実行しましょう!

sudo certbot --nginx -d example.com

 

実行するとずらーっと出てくるので、適切に文字を入力してEnterしていきます。

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): xxxx@xxxxx.xxxx ----①
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
404 Page not found - Let's Encrypt
Let's Encrypt is a free, automated, and open certificate authority brought to you by the nonprofit Internet Security Research Group (ISRG). Read all about our n...
You must agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (A)gree/(C)ancel: A ----② - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Would you be willing 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: N ----③ Obtaining a new certificate Performing the following challenges: http-01 challenge for example.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/conf.d/default.conf Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2 ----④ Redirecting all traffic on port 80 to ssl in /etc/nginx/conf.d/default.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://example.com You should test your configuration at:
SSL Server Test (Powered by Qualys SSL Labs)
A comprehensive free SSL test for your public web servers.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/example.com/privkey.pem Your cert will expire on 2020-05-13. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - 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-le1これで証明書の取得が完了しました。

 

①証明書の有効期限切れが迫るとメールが届く宛先
②利用規約に同意
③メールアドレス情報の共有は同意しない
④http通信が来たらhttpsにリダイレクトする

めちゃくちゃ簡単ですね!

 

nginxの設定ファイル確認

さて、certbotコマンドに「–nginx」オプションを付けたおかげで、nginxの設定ファイルの変更が行われ、SSLサーバ証明書がすでに利用できるようになっているはずです。

設定ファイルを確認してみましょう!

sudo cat /etc/nginx/conf.d/default.conf
server {
    server_name  example.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/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 = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen       80;
    server_name  example.com;
    return 404; # managed by Certbot


}

最低限のSSLサーバ証明書の設定が完成していることが分かると思います。

nginxのdefault.confの中で「server_name」しか変更していないので、細かいチューニングは必要だと思いますが、今回はあくまでもSSLサーバ証明書をcertbotを用いて設定するまでの巻なので、細かいnginxの設定については触れませんのであしからず。

 

最後にnginxの再起動を行っておきましょう。

sudo systemctl restart nginx

再起動後ブラウザからアクセスして証明書情報が確認できるようになっているともいます。

 

certbot自動実行設定

certbotをインストールすると、「certbot-renew.timer」というタイマーユニットが追加されます。

このサービスは定期的に証明書の有効期限を確認して、有効期限が切れそうな場合に証明書を更新してくれるものです。

一般的にcronを用いた定期実行で証明書を更新するという方法が今まで目にしてきたのですが、今回はタイマーユニットを用いた設定を行ってみたいと思う。

 

certbotサービス設定ファイル変更

certbotにて証明書を更新した後にはnginxの再起動を行わないと証明書の変更が認識されない。

そのため、certbotで証明書が更新された際にはnginxの再起動の再起動を行うように「/etc/sysconfig/certbot」を編集します。

29行目あたりに「POST_HOOK=””」という項目があるので、それを編集し「POST_HOOK=”–post-hook ‘systemctl restart nginx’“」に変更します。

まずは/etc/sysconfig/certbotのバックアップ取得

sudo cp -p /etc/sysconfig/certbot /etc/sysconfig/certbot.org~

それから設定ファイルの編集をします。

sudo vim /etc/sysconfig/certbot

変更前との差分も確認しておきましょう。

sudo diff /etc/sysconfig/certbot.org~ /etc/sysconfig/certbot
29c29
< POST_HOOK=""
---
> POST_HOOK="--post-hook 'systemctl restart nginx'"

 

certbot-renew.timerの起動

最後に、今まで設定した内容を用いて定期的に証明書の有効期限を確認して必要であれば更新してくれるタイマーユニット「certbot-renew.timer」を有効にしましょう。

タイマーユニットの有効化と実行開始(–now)

sudo systemctl enable --now certbot-renew.timer

実行されているか確認

sudo systemctl list-timers

以下のような出力になっていればOK

NEXT                         LEFT     LAST                         PASSED    UNIT                         ACTIVATES
Fri 2020-02-14 21:50:40 JST  9h left  Fri 2020-02-14 11:54:18 JST  35min ago certbot-renew.timer          certbot-renew.service
Sat 2020-02-15 12:12:33 JST  23h left Fri 2020-02-14 12:12:33 JST  17min ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service

2 timers listed.
Pass --all to see loaded but inactive timers, too.

上記結果から、次回は2020-02-14 21:50:40 に実行される予定になっていることが分かりますね。

 

これでCentOS7にnginxを導入し且つcertbotを用いてのSSL環境構築と証明書自動取得/更新設定が完了しましたヾ(*´∀`*)ノ

 

めでたしめでたし

 

コメント

  1. superweibu より:

    お久しぶりです。
    私は大阪のホスティング会社で働いています。

    せっかくhttpsにするのなら、http/2やhttp/3(ドラフト25)に対応させてもよいかもしれません。

  2. trippyboy より:

    お久しぶりです!

    大阪のホスティング会社ですか〜!
    思い当たる会社が1つだけあります(^。^)

    http/2は対応すべきですね。
    この記事の続編としてnginxのSSL設定を書いてみようと思います。

    http/3ってのも出てくるんですか!?
    調べてみます!

タイトルとURLをコピーしました