Create SSL Certificate for localhost
Have you ever caught up in a situation where you needed HTTPS on your localhost server for development or testing purposes?
In this article we’ll see how we can create SSL Certificate for localhost.
We’ll move from http://localhost
to https://localhost
with the help of mkcert
tool.
mkcert
is a simple tool for making locally-trusted development certificates. It requires no configuration.
Overview
- Install Nginx to create web server
- Configure Nginx to Listen on port 443(HTTPS).
- Install
mkcert
(Link: mkcert) - Generate SSL Certificate
- Use SSL certificate in Nginx
- Test HTTPS
I’m going to use Nginx to create web server on my machine.
1. To install Nginx in Ubuntu 20.04.
sudo apt update
sudo apt install -y nginx nginx-common
sudo systemctl start nginx
Open your browser and type localhost to open default nginx page.
2. Let’s configure Nginx to listen on 443 (HTTPS).
sudo vi /etc/nginx/conf.d/local.conf
copy paste below sample configuration and save file.
server {
listen 80;
listen [::]:80;
listen 443;
listen [::]:443 ;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
}
Restart Nginx.
sudo systemctl restart nginx
Now let’s try to open Nginx on HTTPS.
you’ll get error something like that.
It’s time to create SSL Certificates for our localhost.
3. Install mkcert
tool (I’m using Ubuntu 20.04).
sudo apt install libnss3-tools #installing certutil
sudo apt install mkcert #install mkcert
mkcert -install
you should see output similar to this 👇.
4. Generate SSL Certificate
mkcert localhost
above command will create 2 files localhost.pem
and localhost-key.pem
in your current working directory.
5. Use SSL certificate in Nginx
we have to tell Nginx to use our mkcert generated pem files.
sudo vi /etc/nginx/conf.d/local.conf
replace configuration with this
server {
listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443 ssl;
ssl_certificate /home/ubuntu/localhost.pem;
ssl_certificate_key /home/ubuntu/localhost-key.pem;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
}
test Nginx conf
sudo nginx -t
restart Nginx to update configuration.
sudo systemctl restart nginx
6. Test HTTPS
we have everything setup and in place.
Now, open your browser and type https://localhost
Now you should be able to use HTTPS with your localhost.