Чтобы включить безопасную связь HTTPS на вашем веб-сервере NGINX. Вам необходимо получить сертификат SSL/TLS от доверенного центра сертификации. Lets Encrypt это некоммерческий центр сертификации, который предлагает бесплатные сертификаты SSL / TLS.
В этом руководстве описывается, как настроить бесплатный сертификат SSL/TLS, выданный компанией Lets Encrypt на сервере Ubuntu 20.04 LTS под управлением сервера Nginx.
Установите Certbot на Ubuntu
Certbot это инструмент с открытым исходным кодом, который упрощает и автоматизирует процесс получения и обновления сертификатов от Lets Encrypt. Мы собираемся установить Certbot с помощью системы развертывания Snap. Snap предварительно установлен на Ubuntu 20.04.
Обновление snapd
Выполните следующие команды для обновления snapd.
$ sudo snap install core $ sudo snap refresh core
Установите certbot snap
Далее требуется установить оснастку Certbot snap.
Примечание: Если вы ранее установили Certbot с помощью стандартной команды apt, то сначала требуется удалить его. Это гарантирует, что привязка Certbot будет работает правильно.
$ sudo apt-get remove certbot
$ sudo snap install classic certbot
certbot 1.11.0 from Certbot Project (certbot-eff✓) installed
Включить команду certbot
После успешной установки оснастки Certbot выполните следующую команду. Эта команда включит certbot.
$ sudo ln-s /snap/bin / certbot / usr/bin/certbot
Получите сертификат Lets Encrypt
Когда вы запустите приведенную ниже команду, certbot проведет вас через остальную часть процесса. Certbot также автоматически обновляет конфигурацию NGINX для активации HTTPS.
$ sudo certbot nginx
Ниже приводится краткое описание того, что certbot предложит вам сделать во время этого процесса.
- Укажите адрес электронной почты, на который будут отправляться уведомления о продлении и безопасности
- Введите Y, чтобы принять условия предоставления услуг
- Введите Y или N, чтобы принять или отклонить предоставление вашего адреса электронной почты разработчикам Certbot
- Подтвердите доменное имя или имена, для которого вы хотели бы включить HTTPS
Выход
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): shola@linoxide.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must agree in order to register with the ACME server. Do you agree? - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: y
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, 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 Account registered.
Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: domain1.com 2: www.domain1.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate numbers separated by commas and/or spaces, or leave input blank to select all options shown (Enter 'c' to cancel): Requesting a certificate for domain1.com and www.domain1.com Performing the following challenges: http-01 challenge for domain1.com http-01 challenge for www.domain1.com Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/domain1 Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/domain1 Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/domain1 Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/domain1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://domain1.com and https://www.domain1.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/domain1.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/domain1.com/privkey.pem Your certificate will expire on 2021-04-10. 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" - 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
Cerbot добавит следующие записи (предложения, показывающие управляемые Certbot) в файл nginx block.
$ cat /etc/nginx/sites-enabled/domain1 # Virtual Host configuration for example.com # # You can move that to a different file under sites-available/ and symlink that # to sites-enabled/ to enable it. # server {
server_name domain1.com www.domain1.com;
root /var/www/domain1.com; index index.html;
location / { try_files $uri $uri/ =404; }
listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain1.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain1.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 = www.domain1.com) { return 301 https://$host$request_uri; } # managed by Certbot
if ($host = domain1.com) { return 301 https://$host$request_uri; } # managed by Certbot
listen 80; listen [::]:80;
server_name domain1.com www.domain1.com; return 404; # managed by Certbot } $
Просмотрите свой веб-сайт, чтобы убедиться, что значок отображается.
Процесс Обновления Сертификата
Сертификаты, выданные компанией Lets Encrypt, действительны в течение 90 дней. Во время установки certbot создает запланированную задачу для автоматического продления срока действия сертификатов до истечения их срока действия. До тех пор, пока вы не измените конфигурацию веб-сервера, вам не придется снова запускать certbot.
Выполните следующую команду, чтобы проверить процесс автоматического продления.
$ sudo certbot renew dry-run
Заключение
В этом руководстве вы узнали, как настроить SSL-сертификат lets encrypt на веб-сервере NGINX, работающем на Ubuntu 20.04.
Вместо Cerbot вы также можете использовать скрипт Acme Shell для автоматической выдачи и продления бесплатных сертификатов от Lets Encrypt.
Если что-то неясно, напишите в разделе комментариев ниже.