Данная инструкция описывает настройку бесплатного https сертификата Let’s Encrypt для Nginx через Certbot.
Certbot — это программа, которая облегчает установку и продление бесплатных https сертификатов от Let’s Encrypt.
Инструкция
Установка пакетов:
_x000D_yum -y install yum-utils_x000D_yum install python2-certbot-nginxNginx config:
_x000D_server {_x000D_ listen 80 default_server;_x000D_ listen [::]:80 default_server;_x000D_ server_name example.com;_x000D__x000D_ root /var/www/domains/example.com;_x000D_ index index.html;_x000D__x000D_ location /.well-known {_x000D_ root /var/www/html;_x000D_ allow all;_x000D_ break;_x000D_ }_x000D_}Установка сертификатов:
_x000D_certbot --nginx --webroot-path=/var/www/htmlПосле выполнения команды, certbot автоматически обновит конфиги Nginx.
Генерация dhparam
Генерирация файла dh4096.pem
_x000D_openssl dhparam -out /etc/letsencrypt/live/dh4096.pem 4096Вставьте в nginx файл настроек сервера следующие строки:
_x000D_ssl_dhparam /etc/letsencrypt/live/dh4096.pem;_x000D__x000D_# Запретить показывать сайт во фрейме11_x000D_#add_header X-Frame-Options DENY;_x000D__x000D_# Использовать отданный сервером Сontent-type, вместо автоматического его определения_x000D_#add_header X-Content-Type-Options nosniff;_x000D__x000D_# Активировать XSS-защиту:_x000D_#add_header X-XSS-Protection "1; mode=block"; Редирект на https
Чтобы добавить редирект, укажите в nginx конфиге следующие строки:
_x000D_if ($ssl_protocol = ""){_x000D_ rewrite ^/(.*) https://$server_name/$1 permanent;_x000D_}_x000D_Второй способ выдать сертификат
Данный способ отличается тем, что не нужно вводить с клавиатуры email, он задается в параметрах, и можно разделить домены по отдельным сертификатам. Т.е. выдать на каждый домен отдельные сертификаты.
_x000D_certbot certonly --non-interactive --agree-tos --email email --cert-name domain --webroot --webroot-path=/var/www/html -d domain1 -d domain2 В поле
После выполнения данной команды нужно вручную прописать в nginx строчки в конце раздела сервер соотвествующего домена.
_x000D_listen 443 ssl; # managed by Certbot_x000D_ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem; # managed by Certbot_x000D_ssl_certificate_key /etc/letsencrypt/live/domain/privkey.pem; # managed by Certbot_x000D_include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot_x000D_ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by CertbotСодержимое файла /etc/letsencrypt/options-ssl-nginx.conf
_x000D_# This file contains important security parameters. If you modify this file_x000D_# manually, Certbot will be unable to automatically provide future security_x000D_# updates. Instead, Certbot will print and log an error message with a path to_x000D_# the up-to-date file that you will need to refer to when manually updating_x000D_# this file._x000D__x000D_#ssl_stapling on;_x000D_ssl_session_cache shared:SSL:2m;_x000D_ssl_session_timeout 1440m;_x000D__x000D_ssl_protocols TLSv1 TLSv1.1 TLSv1.2;_x000D_ssl_prefer_server_ciphers on;_x000D__x000D_ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";Полезные команды
Обновить сертификат:
_x000D_certbot renew --cert-name {cert_name}Удалить сертификат:
_x000D_certbot delete --cert-name {cert_name}Посмотреть список сертификатов:
_x000D_certbot certificatesАвтоматическое продление сертификата
Проверка продления сертификата:
_x000D_certbot renew --dry-run_x000D_Флаг —dry-run нужен, чтобы certbot запустил команду в тестовом режиме, без применения изменений.
Для автоматического продления добавьте в крон:
_x000D_# Edit this file to introduce tasks to be run by cron._x000D_#_x000D_# Each task to run has to be defined through a single line_x000D_# indicating with different fields when the task will be run_x000D_# and what command to run for the task_x000D_#_x000D_# To define the time you can provide concrete values for_x000D_# minute (m), hour (h), day of month (dom), month (mon),_x000D_# and day of week (dow) or use '*' in these fields (for 'any').#_x000D_# Notice that tasks will be started based on the cron's system_x000D_# daemon's notion of time and timezones._x000D_#_x000D_# Output of the crontab jobs (including errors) is sent through_x000D_# email to the user the crontab file belongs to (unless redirected)._x000D_#_x000D_# For example, you can run a backup of all your user accounts_x000D_# at 5 a.m every week with:_x000D_# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/_x000D_#_x000D_# For more information see the manual pages of crontab(5) and cron(8)_x000D_#_x000D_# m h dom mon dow command_x000D__x000D_# Продление сертификата_x000D_26 4 5,10,15,20,25 * * python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew _x000D__x000D_# Перезапуск nginx сервера_x000D_32 6 5,10,15,20,25 * * /bin/systemctl reload nginx.servicesleep нужен, чтобы сервер acme не заблокировал ваш сервер, из-за того что certbot запускается по крону.
Wildcard сертификат
Wildcard не поддерживает автоматическое обновление, поэтому обновлять и устанавливать нужно вручную каждые 3 месяца.
Процесс установки и обновления одинаковый. Вместо example.com укажите свой ДНС адрес. В тексте далее будет использован в качестве примера домен example.com.
Установка:
_x000D_certbot -i nginx -d *.example.com -d example.com --server https://acme-v02.api.letsencrypt.org/directory --preferred-challenges dns --manualСначала certbot спросит о том, что IP адрес должен быть логирован. Чтобы продолжить установку, нужно согласиться.
_x000D_-------------------------------------------------------------------------------_x000D_NOTE: The IP of this machine will be publicly logged as having requested this_x000D_certificate. If you're running certbot in manual mode on a machine that is not_x000D_your server, please ensure you're okay with that._x000D__x000D_Are you OK with your IP being logged?_x000D_-------------------------------------------------------------------------------_x000D_(Y)es/(N)o: YВо время выполнения запросов вам нужно будет добавить две TXT записи, которые укажет certbot.
_x000D_-------------------------------------------------------------------------------_x000D_Please deploy a DNS TXT record under the name_x000D__acme-challenge.example.com with the following value:_x000D__x000D_YOUR-DNS-KEY_x000D__x000D_Before continuing, verify the record is deployed.Сначала вам нужно будет прописать ДНС запись. Подождать пока применяться изменения, проверить изменения командой:
_x000D_nslookup -type=TXT _acme-challenge.example.com_x000D_DNS записи будут две. Нужно будет создать две записи.
Далее certbot спросит, на какие домены устанавливать сертификат
_x000D_-------------------------------------------------------------------------------_x000D_Select the appropriate numbers separated by commas and/or spaces, or leave input_x000D_blank to select all options shown (Enter 'c' to cancel): cВведите c, так как это wildcard сертификат, либо оставьте пустое значение, если вы хотите установить сертификаты на все домены в вашем nginx конфиге.
Если вы не хотите, чтобы был установлен автоматический редирект на https, выберите опцию 1
_x000D_Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access._x000D_-------------------------------------------------------------------------------_x000D_1: No redirect - Make no further changes to the webserver configuration._x000D_2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for_x000D_new sites, or if you're confident your site works on HTTPS. You can undo this_x000D_change by editing your web server's configuration._x000D_-------------------------------------------------------------------------------_x000D_Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1