Setting Up Nginx with SSL for "localhost" on Ubuntu

Mohamed AbdullaMohamed Abdulla
2 min read

Introduction

Howdy๐Ÿ™‹ In this guide, we'll go through creating a self-signed SSL certificate for your localhost, affectionately named "devnext," and configuring Nginx to act as a reverse proxy for a Node.js application. Let's get started!

Prerequisites

  • Ubuntu Server

  • Node.js installed

  • Nginx installed

Steps

1. Generate a Self-Signed SSL Certificate

sudo mkdir /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/devnext.key -out /etc/nginx/ssl/devnext.crt

During this process, when prompted for the Common Name (CN), enter "devnext." and answer basic questions, you can leave them as blank as well

2. Create a New Configuration File:

Open a terminal and use a text editor, such as Nano or Vim, to create a new server block configuration file. For example:

sudo nano /etc/nginx/sites-available/devnext

3. Configure Nginx

Create a new Nginx server block configuration for "devnext":

# /etc/nginx/sites-available/devnext
server {
    listen 443 ssl;
    server_name devnext;

    ssl_certificate /etc/nginx/ssl/devnext.crt;
    ssl_certificate_key /etc/nginx/ssl/devnext.key;

    location / {
        proxy_pass http://localhost:3000;  # Adjust to your Node.js app's port
        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;
    }
}

4. Create a Symbolic Link

sudo ln -s /etc/nginx/sites-available/devnext /etc/nginx/sites-enabled/

5. Test Nginx Configuration

sudo nginx -t

6. Restart Nginx

sudo systemctl restart nginx

7. Set Up Your Node.js Application

Make sure your Node.js application is running on the specified port (e.g., 3000).

8. Access Your Application

Visit https://devnext instead of http://localhost in your web browser. You may encounter a security warning due to the self-signed certificate, but proceed to view the site.


And there you have it, partner! You've successfully lassoed a self-signed SSL certificate for your trusty "devnext" on Nginx. Howdy to a secure localhost and a smooth ride for your Node.js app! If you've got any more questions or feel like saddling up for more web adventures, just holler. Happy trails, and happy coding, friend! ๐ŸŒŸ

10
Subscribe to my newsletter

Read articles from Mohamed Abdulla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mohamed Abdulla
Mohamed Abdulla

Hey there! ๐ŸŒŸ Howdy! ๐Ÿ‘‹ I'm Mohamed Abdulla, a junior year tech enthusiast and developer on a wild ride with Colakin. ๐Ÿš€ Join the adventure! ๐ŸŒ๐Ÿ’ป