centos7のnginxでvirtualhostに対してlet’s encryptを導入

1. certbotをインストール

yum install certbot python2--certbot-nginx

2. virtualhostの設定に「.well-known」を追加

certbotで–webrootを使うと、「[DocumentRoot]/.well-known/acme-challenge/」以下に一時ファイルを作成し、そのファイルへのアクセス可否でドメインとcertbotを実行したサーバの紐付け確認を行うらしい。

今回はRailsを使っているので、nginxの設定ファイルに一時的に以下の設定を追加した。

server {
    listen 80;
    server_name example.com;
    root /var/app/example.com/current/public;

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    location ~ ^/assets/ {
        root /var/app/example.com/current/public;
    }
↓ここから
    location ~ ^/.well-known/ {
        root /var/app/example.com/current/public;
    }
↑ここまで追加

    location / {
        proxy_pass http://hogeapp;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
    }

    client_max_body_size 4G;
}

3. certbotを実行

certbot certonly --webroot -w /var/app/example.com/current/public -d example.com

成功すると以下のメッセージが表示される。

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at
   /etc/letsencrypt/live/example.com/fullchain.pem. Your cert will
   expire on 2017-09-13. To obtain a new or tweaked version of this
   certificate in the future, simply run certbot again. To
   non-interactively renew *all* of your certificates, run "certbot
   renew"
 - 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-le

4. nginxのsslの設定をする

upstream hogeapp {
    server unix:///var/app/example.com/shared/tmp/sockets/example.com-puma.sock;
}

# httpはhttpsにリダイレクト
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;
    root /var/app/example.com/current/public;

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location ~ ^/assets/ {
        root /var/app/example.com/current/public;
    }

    location / {
        proxy_pass http://hogeapp;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
    }

    client_max_body_size 4G;
}

5. nginxとpumaを再起動

これで出来た。

コメント

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