Установка Lets Encrypt. Настройка HTTPS для сайта на nginx

Категория: Nginx

Переключаем сайт на защищенный HTTPS протокол. Получение и управление SSL сертификатами от Lets Encrypt на Ubuntu 18.04.

Установка Certbot

Certbot нужен для управления сертификатами Lets Encrypt.

sudo apt install certbot python3-certbot-nginx -y

Создаем Nginx конфиг сайта для которого будем получать SSL сертификат. Проверяем конфиг Nginx:

sudo nginx -t

Получение SSL сертификата

Установка сертификата для нового сайта:

sudo certbot --nginx -d api.ocr.onedev.net
## или так, если нужен www-домен:
#sudo certbot --nginx -d onedev.net -d www.onedev.net -d api.onedev.net
Пошаговая генерация SSL-сертификата в интерактивном режиме
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)
: ВАШ_EMAIL_ДЛЯ_УВЕДОМЛЕНИЙ
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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: N
Obtaining a new certificate Performing the following challenges: http-01 challenge for api.ocr.onedev.net Waiting for verification... Cleaning up challenges Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/api.ocr.onedev.net.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/sites-enabled/api.ocr.onedev.net.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Congratulations! You have successfully enabled https://api.ocr.onedev.net You should test your configuration at: https://www.ssllabs.com/ssltest/analyze.html?d=api.ocr.onedev.net - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/api.ocr.onedev.net/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/api.ocr.onedev.net/privkey.pem Your cert will expire on 2020-12-30. 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
Примечание

Если вы планируете редиректить www.site.com на site.com - не обязательно генерировать сертификат для домена www.site.com.

При генерации сертификата нужно в одной команде указывать опциями все используемые под-домены!

Чтобы перенаправить www на non-www проверьте конфиг /etc/nginx/sites-available/ikino.club.conf, и на всякий проверьте конфиг /etc/nginx/sites-enabled/default.conf (да, именно sites-enabled/default).

Пример nginx конфига с перенаправлением http://www. и https://www. на https://site.com:
server {
    listen 80;
    server_name site.com www.site.com;
    
    if ($host = site.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = www.site.com) {
        return 301 https://site.com$request_uri;
    }
    
    return 404; # managed by Certbot
}

server {
    server_name site.com www.site.com;
    root        /var/www/site.com/public/;
    index       index.html index.php;

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

    // ... ваша дополнительная конфигурация
}


Примечание

Если что-то пошло не так, попробуйте сгенерировать сертификаты без активации nginx-плагина (без параметра --nginx):

sudo certbot certonly --webroot -w /var/www/ikino.club -d ikino.club -d www.ikino.club

*Сертификаты и ключи будут скопированы в /etc/letsencrypt/live/site.com/.

Обслуживание

Удалить сертификат:

sudo certbot delete --cert-name site.com

Проверить статус сервиса обновления сертификатов:

sudo systemctl status certbot.timer

Протестировать процесс обновления сертификатов:

sudo certbot renew --dry-run

#https, #ssl, #lets encrypt

категория: Nginx