Installation of SSL Сertificate in NGINX

We need two files to install a certificate in NGINX, namely the certificate itself (usually of .crt extension) and the private key (usually of .key extension). Sometimes a CA (certification authority) sends multiple files, some of which are a chain of certificates, and one of those files is your private key.

If there are multiple files for a chain of certificates, you should merge them using the following template:


        
-----BEGIN CERTIFICATE-----
#здесь должен быть Ваш сертификат
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
#здесь должен быть промежуточный сертификат
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
#здесь должен быть корневой сертификат
-----END CERTIFICATE-----
 

Save the resulting file as domain.crt, where domain is the name of your domain. In fact, it doesn't matter how you name this file, what matters is the content, but for convenience it is better to name it according to the confirmed domain.

Now upload two files (domain.crt and domain.key) to the server, preferably in the /etc/ssl/ or /etc/nginx/ssl/ directories, but it is not obligatory.

Now let's configure NGINX. In the existing server{} section, open the configuration file, which describes your domain, and change the line


        
listen 80;
 

to


        
listen 443 ssl http2; # или просто listen 443 ssl;
 
ssl_certificate /etc/ssl/domain.crt;
ssl_certificate_key /etc/ssl/domain.key;
 

Pay attention: this is the full path to the certificate and private key files. If you’ve placed these files elsewhere, then you need to change these lines.

If you want to redirect from HTTP to HTTPS, then add another section with the following content:


        
server {
    if ($host = domain.ru) {
        return 301 https://$host$request_uri;
    }
 
    listen 80;
    server_name domain.ru;
    return 404;
 
}
 

The domain.com address should be replaced with the address of your site.

Now check the changes:


$ sudo nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

If there were no problems, then we did not make any syntax errors (logical errors are not checked here). Restart NGINX:


$ sudo systemctl restart nginx

Now let's check your website. Access it via browser, a lock icon should appear left from the address bar.

Later on, you will only need to specify the path to the new certificates and make sure to restart NGINX.