Setup Nginx with SSL Certificate(Ubuntu)
Step 1 – Installing Nginx
Because Nginx is available in Ubuntu’s default repositories, it is possible to install it from these repositories using the apt
packaging system.
Since this is our first interaction with the apt
packaging system in this session, we will update our local package index so that we have access to the most recent package listings. Afterwards, we can install nginx
:
sudo apt update
sudo apt install nginx
After accepting the procedure, apt
will install Nginx and any required dependencies to your server.
Step 2– Configure Nginx default behaviour
locate default file on
cd /etc/nginx/sites-enabled/
modify file
sudo vim /etc/nginx/sites-enabled/default
Set modify example1.com www.example1.com , example2.company.com www.example2.company.com
with your custom domain or IP.
server {
listen 80;
server_name example1.com www.example1.com ;
location / {
return 301 https://www.example1.com$request_uri;
}
}
server {
listen 80;
server_name example2.company.com www.example2.company.com ;
location / {
return 301 https://www.example2.company.com$request_uri;
}
}
Step 3– Validate and Restart Nginx Configuration
validate our configuration with sudo nginx -t
After validating the configuration restart the nginx with
Command:sudo systemctl restart nginx
Step 4– Install Certbert
Install Certbot and Certbot plugin for Nginx
$ sudo apt-get install certbot
$ sudo apt-get install python3-certbot-nginx
Step 5-Obtain the SSL/TLS Certificate
Run the following command to generate certificates with the NGINX plug‑in:
$ sudo certbot --nginx -d example.com -d www.example.com
Step 5-Automatically Renew Let’s Encrypt Certificates
Open the Corntab file.
$ crontab -e
Add the
certbot
command to run daily. In this example, we run the command every day at noon. The command checks to see if the certificate on the server will expire within the next 30 days, and renews it if so. The--quiet
directive tellscertbot
not to generate output.0 12 * * * /usr/bin/certbot renew --quiet
Let’s Encrypt uses the client Certbot to install, manage, and automatically renew the certificates they provide. In the case where your certificate does not automatically renew on your Droplet, you can manually trigger the renewal at anytime by running:
sudo certbot renew
Copy
If you have multiple certificates for different domains and you want to renew a specific certificate, use:
certbot certonly --force-renew -d example.com
Copy
The
--force-renew
flag tells Certbot to request a new certificate with the same domains as an existing certificate. The-d
flag allows you renew certificates for multiple specific domains.To verify that the certificate renewed, run:
sudo certbot renew --dry-run
Copy
If the command returns no errors, the renewal was successful.
Note:: do not keep more than one file of sites-enabled it will cause issue
nginx: [warn] conflicting server name