Crmgo Blog

Configuring SSL (HTTPS) in Nginx

Configuring SSL (HTTPS) in Nginx

To protect the traffic transmitted between the server and the client, you can use the SSL encryption mechanism. Since nginx often acts as a frontend for Apache, it is better to offload the encryption to it. Using a mass self-signed certificate. Let's configure the use of a single self-signed certificate for multiple…

Configuring SSL (HTTPS) in Nginx

To protect the traffic transmitted between the server and the client, you can use the SSL encryption mechanism.

Since nginx often acts as a frontend for Apache, it is better to offload the encryption to it.

Using a mass self-signed certificate

Let's configure the use of a single self-signed certificate for multiple websites.

Create a common SSL configuration file:

/etc/nginx/ssl.conf

# Подключение самоподписанного сертификата
# генерация сертификата:
# openssl req -new -x509 -days 9999 -nodes -out cert.pem -keyout cert.key

ssl			on;
ssl_protocols		SSLv3 TLSv1;
ssl_certificate		/etc/nginx/ssl/cert.pem;
ssl_certificate_key	/etc/nginx/ssl/cert.key;

 

Create a folder where we will store the certificates:

mkdir /etc/nginx/ssl

To increase security, restrict access to the certificates:

chown nginx:nginx /etc/nginx/ssl
chmod 700 /etc/nginx/ssl

Go to this folder and generate the certificate:

cd /etc/nginx/ssl
openssl req -new -x509 -days 9999 -nodes -out cert.pem -keyout cert.key

During generation, you will be asked to provide some data. Since we are creating the certificate for ourselves, it is not necessary to fill them in.

Now, to enable encryption for the required sites, we will use the following template:

in the nginx site configuration:

server {
        listen          *:443;       # порт https
        server_name     my.site.com; # ваш сайт

        include	/etc/nginx/ssl.conf; # подключение конфигурации ssl

        ...
}

 

Example with forced redirection from http to https:

in the nginx site configuration:

server {
        listen          *:443;       # порт https
        listen		*:80;        # порт http
        server_name     my.site.com; # ваш сайт

        include	/etc/nginx/ssl.conf; # подключение конфигурации ssl
        if ( $scheme = "http" ) {
	      rewrite ^/(.*)$	https://$host/$1 permanent;
        }
   }
? или
server {
        listen 80;
        listen [::]:80;
        server_name .domain.com;
        rewrite     ^ https://domain.com$request_uri? last;
}
Пожалуйста, поправьте, это важно. Вместо last можно использовать permanent или нечто другое, вот все флаги:
    last — завершает обработку текущего набора директив ngx_http_rewrite_module, после чего ищется соответствие URI и location;
    break — завершает обработку текущего набора директив ngx_http_rewrite_module;
    redirect — возвращает временный редирект с кодом 302; используется, если заменяющая строка не начинается с "http://";
    permanent — возвращает постоянный редирект с кодом 301.
        ...
}

 

After configuration, you need to reload nginx:

/etc/init.d/nginx reload

Everything is ready. To access the site, you should use the https protocol - https://my.site.com

Since the certificate is self-signed, the browser will ask you to confirm an exception for its use.

Additional options for creating an SSL certificate

Creating a certificate with the command:

openssl req -new -x509 -days 9999 -nodes -out cert.pem -keyout cert.key

requests some information for creating the certificate, which can be skipped.

But if you are interested, here is a description of the parameters:

Value Description Required parameter?
C Two-letter country code (Country) no
ST Name of the region/area/canton/republic/… (State Name) no
L Name of the city/town/… (Locality Name) no
O Organization name (Organization Name) no
OU Department name (Organization Unit) no
CN Certificate name; for server certificates, the domain name of the site is used (Common Name) yes
emailAddress Email address (E-mail address) no

To avoid entering these parameters interactively, you can use the -subj option:

openssl req -new -x509 -days 9999 -nodes -subj /C=RU/O=My\ site/CN=my.site.com/emailAddress=admin@site.com -out cert.pem -keyout cert.key


Note: This post may be AI-assisted and then human-edited. Editorial responsibility: Dmytro Lomaka, Kaltenkirchen.