Selfsigned Certificate In Wsl2 Linux Nginx

26 Sep 2020 - Alejandro Piña

A self-signed certificate is used when you need create local environments to build websites or applications that needs a hostname with SSL/TLS connection whithout CA authorities

How To

Prerequisites

  • Install OpenSSL
  • Install Nginx
  • Install Chrome/Chromium/Edge

Create CRT and KEY files with OpenSSL

Open a terminal

cd ~
mkdir local_certificates
cd local_certificates
openssl req -x509 -newkey rsa:4096 \
-sha256 -days 3650 -nodes \
-keyout local.ultranaco.com.key \
-out local.ultranaco.com.crt \
-subj "/CN=local.ultranaco.com" \
-addext "subjectAltName=DNS:local.ultranaco.com"

Copy certificate and key file into ssl folder

sudo cp local.ultranaco.com.crt /etc/ssl/certs/local.ultranaco.com.crt
sudo cp local.ultranaco.com.key /etc/ssl/private/local.ultranaco.com.key

Raise a local application with custom hostname in Nginx

Creating application with Hello World message

cd ~
mkdir myapplication
cd myapplication
echo "Hello World" > index.html

Creating configuration file to serve index.html on the port 443 with custom hostname

cd /etc/nginx/sites-available
sudo touch local.ultranaco.com.site

File contents local.ultranaco.com.site

server {
        listen 443 ssl http2;
        server_name local.ultranaco.com;

        ssl_certificate /etc/ssl/certs/local.ultranaco.com.crt;
        ssl_certificate_key /etc/ssl/private/local.ultranaco.com.key;

        ssl_protocols TLSv1.2 TLSv1.1 TLSv1;

        root /home/ultranaco/myapplication;
        index index.html;

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

Enabling application with symlink file

cd ../sites-enabled
sudo ln -s /etc/nginx/sites-available/local.ultranaco.com.site local.ultranaco.com.site
sudo service nginx restart

Append the below text line into /etc/hosts file for linux, if you are working on windows with WSL2 /Windows/System32/drivers/etc/hosts file

127.0.0.1    local.ultranaco.com

Make certificate trusted

Open your application with Chrome/Chromium/Edge with the following url https://local.ultranaco.com, you´ll see and error related with the certificate.

To fix the error you need to export certificate with extension .cer

Make certificate trusted

Go to Settings and search Manage Certificates to import your certificate with extension .cer

Trusted Root Certification Authorities

Restart Chrome/Chromium/Edge and now your certificate es valid and trusted

Valid and Trusted Certificate

Enjoy it, doggy!