Create an SSL key and certificate and Configure SSL with Nginx

Author: Al-mamun Sarkar Date: 2020-04-14 15:51:36

Create an SSL key and certificate and Configure SSL with Nginx. The following commands show how to create SSL Key and Certificate and configure SSL on the Nginx server. 

 

Install OpenSSL:

apt install openssl -y

 

Create an SSL key and certificate:

openssl req -batch -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx.key -out /etc/ssl/certs/nginx.crt -batch

 

Update artofcse.local.conf configuration file:

vim /etc/nginx/conf.d/artofcse.local.conf

Add the following codes:

server {
    listen 80 default_server;
    return 301 https://$server_addr$request_uri;
}

 

listen 443 ssl default_server;
ssl_certificate /etc/ssl/certs/nginx.crt;
ssl_certificate_key /etc/ssl/private/nginx.key;

 

New Nginx configuration:

server {
    listen 80 default_server;
    return 301 https://$server_addr$request_uri;
}


server {
        listen 443 ssl default_server;
        ssl_certificate /etc/ssl/certs/nginx.crt;
        ssl_certificate_key /etc/ssl/private/nginx.key;

        server_name artofcse.local www.artofcse.local;
        index index.html index.htm index.php;
        root /var/www/artofcse.local;

        access_log /var/log/nginx/artofcse.local.access.log;
        error_log /var/log/nginx/artofcse.local.error.log;

        location / {
                try_files $uri $uri/ =404;
        }

        location /images {
                autoindex on;
                access_log /var/log/nginx/artofcse.local.images.access.log;
                error_log /var/log/nginx/artofcse.local.images.error.log;
        }

        location /appointments/ {
                allow 192.168.33.0/24;
                allow 10.0.0.0/8;
                deny all;
        }

        location /deny/ {
                deny all;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
                fastcgi_intercept_errors on;
        }

        error_page 403 /403.html;
        location = /403.html {
                internal;
        }

        error_page 404 /404.html;
        location = /404.html {
                internal;
        }
}

 

Test configuration:

nginx -t

 

Reload Nginx configuration:

systemctl reload nginx

 

Now you can visit site by https protocol.