How to add SSL to Node.js using NGINX on AWS ubuntu instance
In this tutorial we will briefly go through the process of adding ssl to Node.js using Nginx. You can follow the same steps if you are using any other cloud service provider’s service.
In this article we will cover:
- Installing and configuring Nginx for reverse proxy
- Securing Node.js application with LetsEncrypt SSL
Configuring NGINX and Reverse proxy
We have to run the below command to install NGINX:
sudo npm install nginx
After NGNIX is installed and configured we need to setup the reverse proxy and redirect our application to port 80. To do so we have to edit the following file with our Node.js app running port as below
command to open the file
sudo nano /etc/nginx/sites-available/default
After opening the file we need to add the following configuration
server_name www.yourdomain.com;location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection ‘upgrade’;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
After adding the above mentioned configuration we need to restart the NGINX
sudo service nginx restart
Yey, Finally we need secure our node.js with SSL encryption. We can do this by using LetsEncrypt library easily. To add the library we need to follow these steps
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python3-certbot-nginx
Once the installation is completed using the certbot cli we need to generate the SSL certificate for our domain. For this we need to run the following command
sudo certbot — nginx -d yourdomain.com -d www.yourdomain.com
Once you run the above command you will be prompted to enter the email address. After you enter the email the SSL certificate will get generated. Now you should be able to connect your application via HTTPS.