Как установить SSL-сертификат Lets Encrypt в Nginx в Ubuntu 20.04

В этом руководстве вы узнаете, как установить, certbot который взаимодействует с Let's Encrypt. Мы создадим SSL сертификат для нашего example.com домена и адаптируем Nginx конфигурацию, а также ufw конфигурацию.

Шаг 1 - Установите Certbot

Сначала обновите свой сервер:
user@example.com:~$ sudo apt-get update && sudo apt-get upgrade -y
Затем мы собираемся установить Certbot:
user@example.com:~$ sudo apt install certbot python3-certbot-nginx

Шаг 2. Разрешите трафик HTTPS

В предыдущих руководствах мы разрешали HTTPтрафик только через наш брандмауэр. Итак, ваш ufwстатус должен выглядеть так:
user@example.com:~$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Nginx HTTP                 ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Nginx HTTP (v6)            ALLOW       Anywhere (v6)
Теперь нам нужно изменить это, чтобы также разрешить HTTPSтрафик:
user@example.com:~$ sudo ufw allow 'Nginx Full'
user@example.com:~$ sudo ufw delete allow 'Nginx HTTP'
Наш новый ufwстатус выглядит так:
user@example.com:~$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Nginx Full (v6)            ALLOW       Anywhere (v6)

Шаг 3 - Получите сертификат SSL

На этом этапе мы попросим certbotпредоставить нам SSLсертификат. Certbotтакже автоматически адаптирует нашу Nginxконфигурацию, которую мы установили ранее.
Для этого нам нужно выполнить следующую команду:
user@example.com:~$ sudo certbot --nginx -d example.com
Если вы будете использовать оба, example.comи www.example.comвам нужно сообщить об этом certbot на этом этапе.
user@example.com:~$ sudo certbot --nginx -d example.com -d www.example.com

Шаг 3.1 - Запрос Certbot

Certbot предложит вам следующее:
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):
Укажите адрес электронной почты, который вы регулярно проверяете, так как Let's Encrypt будет предупреждать вас по электронной почте об истечении срока действия сертификатов.
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 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:
Здесь вам нужно принять условия обслуживания и выбрать, хотите ли вы подписаться на информационный бюллетень EFF.
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/sites-enabled/example.com

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/sites-enabled/example.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://example.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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 2021-11-20. 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-le
Вы только что получили SSLсертификат!
Ваша новая Nginxконфигурация должна выглядеть следующим образом:
server {

  root /var/www/example.com/html;
  index index.html;

  server_name example.com;

  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/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;
  listen [::]:80;

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


}

Заключение

Добавить комментарий

Автору будет очень приятно узнать обратную связь о своем руководстве.

Комментариев 0