Secure Nginx web server with Let's Encrypt on CentOS 7 - Get a Free SSL Certificate

You're founding this page because of you already know what is Nginx and Let's Encrypt. In this simple tutorial you will learn how to install and configure Nginx and Let's Encrypt on CentOS 7.

If you're using Amazon web services or Google Cloud Platform or any other cloud service first make sure you have allowed HTTP and HTTPS access to the VM.

Update your CentOS 7

sudo yum update

Installing and configuring Nginx

sudo yum install nginx

Next we need to point a domain to the server. Run following command.

sudo vi /etc/nginx/nginx.conf

Find the server_name_; line and replace the _ underscore with your domain name.
(By clicking Insert button on keyboard you can edit the file. Press Esc and type :wq and hit Enter will save your config)

e.g: server_name;

By running below commands make sure your setting is successful.

sudo systemctl start nginx
sudo systemctl enable nginx
sudo nginx -t 

Setting Firewall

We also need to allow HTTP (port:80) and HTTPS (port:443) via VM local firewall.

If you're running firewalld, run below commands.

sudo firewall-cmd --add-service=http 
sudo firewall-cmd --add-service=https 
sudo firewall-cmd --runtime-to-permanent

If you're running iptables, run following commands. 

sudo iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT 
sudo iptables -I INPUT -p tcp -m tcp --dport 443 -j ACCEPT 

If you're not sure what is your firewall, just run firewalld and iptables configuration commands. It will not damage your settings.

Obtaining a Certificate using Nginx plugin

Run below command, with your domain names. It will ask you simple questions. Just answer them.

sudo certbot --nginx -d -d 

Updating Diffie-Hellman Parameters

Now you successfully installed and configured done Nginx web server with Let's Encrypt. But if you're checking SSL via SSL Labs, it will show you a B Grade due to weak Diffie-Hellman parameters. We can fix this by creating a new dhparam.pem file and adding it to our server block.

Run following command.

sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048 

This will take a long time to generate.

Setting Up Auto Renewal

Let's Encrypt certificates only valid for ninety(90) days. So when it will near to expire soon, you will get an email notification. Running following command you can renew certificate yourself.

certbot renew 

But it is easy when we use crone jobs. 

Run following command:

sudo crontab -e 

Add following line and save it.

0 0 1 * * /usr/bin/certbot renew --quiet

It will renew your certificate every month. If you need change to custom time period please find the Configuring Cron Tasks on CentOS docs.

You're all done. If anything wrong please let me know.