# Nginx Reverse Proxy with Free SSL (Let’s Encrypt) for Node.js on a VPS

## The starting point

You’ve deployed a Node.js app to a VPS and it works, but only at an address like `http://203.0.113.10:3000`. That setup has real problems:

-   **Traffic is unencrypted.** Logins, cookies and API tokens travel in plain text, and browsers mark the site as "Not secure".
    
-   **The Node port is exposed.** Anyone on the internet can talk to your app directly, bypassing anything you put in front of it.
    
-   **The URL is ugly.** Users, webhooks and API clients expect `https://yourdomain.com`, not an IP address and a port.
    
-   **Features break without HTTPS.** Secure cookies, many browser APIs and a growing number of third-party webhooks require it.
    

The standard fix is to put **Nginx** in front of your app as a reverse proxy and let it handle HTTPS using a free certificate from **Let’s Encrypt**. In this guide we’ll set that up step by step.

```java
Browser ──HTTPS (443)──▶ Nginx ──HTTP──▶ Node.js (127.0.0.1:3000)
                          │
                 terminates SSL, redirects
                 HTTP (80) to HTTPS
```

## Why put Nginx in front of Node.js?

-   **SSL termination.** Nginx handles the certificate and encryption, and your app keeps speaking plain HTTP on localhost.
    
-   **No root needed for Node.** Ports 80 and 443 are privileged, and Nginx owns them, so your app can run as a normal user on port 3000.
    
-   **One server, many apps.** Nginx can route different domains to different Node apps on the same VPS.
    
-   **A hardened front door.** Nginx copes well with slow clients, large numbers of connections, request size limits and (later) rate limiting.
    

## What you need

-   A VPS running **Ubuntu 22.04 or 24.04** with SSH access and a user with `sudo` (the commands are nearly identical on Debian)
    
-   A **domain name** you control. This guide uses `example.com`, so replace it with your own everywhere
    
-   A Node.js app that listens on a port (we’ll use `3000`)
    

## Step 1: Point your domain to the server

In your domain registrar’s or DNS provider’s dashboard, create these records:

| Type | Name | Value |
| --- | --- | --- |
| A | @ | your VPS’s IPv4 address |
| A | www | your VPS’s IPv4 address |

Only add `AAAA` (IPv6) records if your VPS really has working IPv6. If an `AAAA` record exists, Let’s Encrypt tries IPv6 first, and validation fails when your server isn’t reachable that way.

Check that DNS has propagated:

```bash
dig +short example.com
dig +short www.example.com
```

Both should print your server’s IP. Propagation usually takes a few minutes but can take longer. **Don’t continue until this works**, because Certbot needs it in Step 7.

## Step 2: Run your Node.js app on localhost

Here is a minimal Express app. Two details matter: it listens on `127.0.0.1` only, so the outside world can reach it **only through Nginx**, and it trusts the proxy so it sees the real visitor IP and protocol.

```javascript
// app.js
import express from 'express';

const app = express();

// Behind Nginx, trust the first proxy so req.ip and req.protocol are correct
app.set('trust proxy', 1);

app.get('/', (req, res) => {
  res.json({
    message: 'Hello from Node.js behind Nginx',
    ip: req.ip,
    protocol: req.protocol,
  });
});

const PORT = process.env.PORT ?? 3000;

// Listen on localhost only: Nginx is the only way in
app.listen(PORT, '127.0.0.1', () => {
  console.log(`Listening on 127.0.0.1:${PORT}`);
});
```

(This uses ES module syntax, so your `package.json` needs `"type": "module"`.)

Keep it running with **PM2**, so it restarts after crashes and server reboots:

```bash
sudo npm install -g pm2
pm2 start app.js --name my-app
pm2 save
pm2 startup
```

`pm2 startup` prints a command beginning with `sudo env PATH=...`. Copy it and run it to enable start on boot.

Confirm the app answers locally:

```bash
curl http://127.0.0.1:3000
```

## Step 3: Install Nginx

```bash
sudo apt update
sudo apt install nginx -y
sudo systemctl status nginx
```

Press `q` to leave the status view. Open `http://example.com` in a browser, and you should see the default "Welcome to nginx!" page.

## Step 4: Open the firewall

Ubuntu’s `ufw` firewall knows about Nginx through application profiles:

```bash
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status
```

-   `OpenSSH` **first.** If you enable the firewall without allowing SSH, you lock yourself out. If you run SSH on a non-default port, allow that port instead.
    
-   `Nginx Full` opens ports 80 (HTTP) and 443 (HTTPS).
    
-   **Do not open port 3000.** Your app only listens on localhost anyway.
    

Many VPS providers also have a **cloud firewall or security group** in their dashboard. Make sure ports 80 and 443 are allowed there too.

## Step 5: Create the Nginx server block

Create a config file for your site:

```bash
sudo nano /etc/nginx/sites-available/example.com
```

Paste this:

```nginx
# Allows WebSocket upgrades while leaving normal requests untouched
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}
```

What each part does:

-   `proxy_pass` forwards every request to your Node app.
    
-   `Host` passes the original domain name through to your app.
    
-   `X-Forwarded-For` **and** `X-Real-IP` carry the visitor’s real IP address. Without them, your app sees every request as coming from `127.0.0.1`.
    
-   `X-Forwarded-Proto` tells your app whether the visitor used `http` or `https`. This is what `trust proxy` in Express reads.
    
-   `Upgrade` **and** `Connection` make WebSockets (and Socket.IO) work through the proxy.
    

If you later host a second app on the same server, define the `map` block **only once** (for example in `/etc/nginx/conf.d/websocket.conf`). Declaring `$connection_upgrade` twice makes Nginx fail with a duplicate variable error.

Enable the site, test the configuration and reload Nginx:

```bash
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

`nginx -t` should report that the syntax is ok and the test is successful. You can optionally remove the default site, so requests for unknown hostnames no longer get the welcome page:

```bash
sudo rm /etc/nginx/sites-enabled/default
sudo systemctl reload nginx
```

Test it:

```bash
curl -i http://example.com
```

You should get a `200 OK` and your app’s JSON, with your own IP and `"protocol":"http"`:

```json
{"message":"Hello from Node.js behind Nginx","ip":"198.51.100.25","protocol":"http"}
```

If you see **502 Bad Gateway** instead, Nginx can’t reach your app. Check `pm2 status`, run `curl http://127.0.0.1:3000`, and look at `sudo tail /var/log/nginx/error.log`.

## Step 6: Install Certbot

**Certbot** is the official tool for getting certificates from Let’s Encrypt and installing them into Nginx. Its maintainers recommend installing it as a snap:

```bash
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
```

If you previously installed Certbot with `apt`, remove it first with `sudo apt remove certbot` to avoid conflicts. Snap comes preinstalled on Ubuntu. On Debian, install it first with `sudo apt install snapd`.

## Step 7: Get the certificate

Request a certificate for both names and let Certbot configure Nginx:

```bash
sudo certbot --nginx -d example.com -d www.example.com
```

Certbot will ask for:

1.  **An email address.** It’s used for important account and security notices. Let’s Encrypt no longer sends certificate expiry reminders, so don’t rely on email to tell you about a failed renewal. We’ll set up a proper check in Step 9.
    
2.  **Agreement to the terms of service.**
    
3.  **Optionally, the EFF mailing list.** Either answer is fine.
    

Depending on your Certbot version, you may also be asked whether to redirect HTTP traffic to HTTPS. Choose the redirect option.

Behind the scenes, Certbot proves you control the domain by answering a challenge over **port 80**, which is why DNS and the firewall had to be right first. It then stores the certificate in `/etc/letsencrypt/live/example.com/` and edits your Nginx config. Open your site file again and you’ll see something like this (the lines marked `managed by Certbot` are added automatically):

```nginx
server {
    server_name example.com www.example.com;

    location / {
        # ...your proxy settings, unchanged...
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 404; # managed by Certbot
}
```

The first block now serves HTTPS and proxies to your app. The second block catches plain HTTP and redirects it to HTTPS.

Need a wildcard certificate such as `*.example.com`? That requires a different validation method (DNS-01) and a Certbot DNS plugin, which is outside the scope of this guide.

## Step 8: Verify HTTPS

Check that HTTP now redirects:

```bash
curl -I http://example.com
```

You should see `301 Moved Permanently` with a `Location: https://example.com/` header. Then check HTTPS itself:

```bash
curl -i https://example.com
```

The JSON should now say `"protocol":"https"`. That confirms the whole chain works: Nginx sends `X-Forwarded-Proto`, and Express reads it because of `trust proxy`. Open the site in a browser and you’ll see the padlock. For a deeper review of your TLS setup, the free [SSL Labs test](https://www.ssllabs.com/ssltest/) grades it.

## Step 9: Automatic renewal (and knowing when it fails)

Let’s Encrypt certificates are valid for **90 days**, and the Certbot snap installs a systemd timer that renews them automatically. Check that the timer exists, then run a simulated renewal:

```bash
sudo systemctl list-timers | grep certbot
sudo certbot renew --dry-run
```

The dry run should end with a message that all simulated renewals succeeded. Certbot reloads Nginx after a real renewal, so you don’t need to do that yourself.

Automation matters more every year. Let’s Encrypt has announced that its default certificate lifetime will drop to **64 days from February 10, 2027**, and to **45 days from February 16, 2028**. Renewing by hand will stop being practical, and any script that renews on a fixed long interval would no longer be enough.

### Get a Telegram alert before a certificate expires

Automatic renewal can still fail silently: the timer stops, DNS changes, or the firewall starts blocking port 80. Since Let’s Encrypt no longer emails expiry warnings, add a small check of your own. This script looks at the certificate your site is actually serving and alerts you through the Telegram bot from our alert bot post when it is close to expiry. Create `/usr/local/bin/check-cert.sh`:

```bash
#!/bin/bash
# Sends a Telegram alert if the certificate served by your site is close to expiring.

DOMAIN="example.com"
PORT=443
WARN_DAYS=7
BOT_TOKEN="123456789:AAH..."
CHAT_ID="987654321"

END_DATE=$(echo | timeout 10 openssl s_client -servername "$DOMAIN" -connect "$DOMAIN:$PORT" 2>/dev/null \
  | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)

if [ -z "$END_DATE" ]; then
  MESSAGE="🚨 Could not read the SSL certificate for $DOMAIN"
else
  DAYS_LEFT=$(( ( $(date -d "$END_DATE" +%s) - $(date +%s) ) / 86400 ))
  if [ "$DAYS_LEFT" -lt 0 ]; then
    MESSAGE="🚨 The SSL certificate for $DOMAIN has expired"
  elif [ "$DAYS_LEFT" -lt "$WARN_DAYS" ]; then
    MESSAGE="⚠️ The SSL certificate for $DOMAIN expires in $DAYS_LEFT days"
  else
    exit 0
  fi
fi

curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
  -d chat_id="$CHAT_ID" \
  --data-urlencode text="$MESSAGE" > /dev/null
```

Because the script contains your bot token, restrict access to it, then schedule it once a day:

```bash
sudo chmod 700 /usr/local/bin/check-cert.sh
sudo crontab -e
```

Add this line to run it every morning at 09:00:

```sql
0 9 * * * /usr/local/bin/check-cert.sh
```

To test it, temporarily set `WARN_DAYS=100`, run `sudo /usr/local/bin/check-cert.sh`, and a message should arrive on your phone. Don’t forget to set it back to `7`.

## Step 10: Optional hardening

These small changes are worth making once HTTPS works.

**Allow larger uploads.** Nginx rejects request bodies over 1 MB by default, which shows up as a `413 Request Entity Too Large` error. Raise the limit inside the HTTPS `server` block:

```nginx
client_max_body_size 10m;
```

**Enable HSTS.** This header tells browsers to only ever use HTTPS for your site. Add it to the HTTPS `server` block:

```nginx
add_header Strict-Transport-Security "max-age=31536000" always;
```

Only do this once you’re sure HTTPS works everywhere, because browsers will remember the rule for a year. Be careful with `includeSubDomains`, since it applies to every subdomain.

**Hide the Nginx version.** In `/etc/nginx/nginx.conf`, inside the `http` block, uncomment or add:

```nginx
server_tokens off;
```

**Enable HTTP/2** for faster page loads. On Nginx 1.25.1 and newer, add `http2 on;` to the HTTPS `server` block. On older versions, add `http2` to the `listen 443 ssl` line. Check your version with `nginx -v`.

After any change, run `sudo nginx -t` and then `sudo systemctl reload nginx`.

## Troubleshooting

-   **Certbot fails with a timeout or "connection refused".** DNS doesn’t point at this server yet, or port 80 is blocked by `ufw` or your provider’s firewall. Fix that first, because repeated failed attempts can trigger Let’s Encrypt’s rate limits. When experimenting, add Certbot’s `--staging` flag so test attempts don’t count against your real limits.
    
-   **502 Bad Gateway.** Your Node app isn’t running, or it listens on a different port. Check `pm2 status`, `curl http://127.0.0.1:3000` and `/var/log/nginx/error.log`.
    
-   **Redirect loop in the browser.** Your app (or a Cloudflare "Flexible" SSL setting) thinks requests are plain HTTP and keeps redirecting to HTTPS. Make sure Nginx sends `X-Forwarded-Proto`, your app trusts the proxy, and Cloudflare uses "Full (strict)" if you use it.
    
-   **Every visitor shows the same IP, or** `req.secure` **is** `false`**.** Express is missing `app.set('trust proxy', 1)`.
    
-   `nginx -t` **reports a duplicate variable.** The `map` block for `$connection_upgrade` is defined in more than one file.
    
-   **Site works on the domain but not on** `www`**.** The `www` DNS record is missing, or `www.example.com` wasn’t included in the Certbot command.
    

## Recap

1.  Point your domain’s DNS at the VPS
    
2.  Run your Node app on `127.0.0.1:3000` with PM2
    
3.  Install Nginx and open ports 80 and 443 (not 3000)
    
4.  Add a reverse proxy server block that forwards the right headers
    
5.  Install Certbot and request a certificate with `certbot --nginx`
    
6.  Verify the HTTPS redirect and confirm renewal with `certbot renew --dry-run`
    
7.  Monitor the certificate yourself with a Telegram alert
    

You now have your Node.js app on a clean `https://` address, behind a reverse proxy that handles encryption and keeps your app’s port off the public internet, with certificates that renew on their own and an alert if they ever don’t.

---

*Published via [ZyVOP](https://zyvop.com/nginx-reverse-proxy-with-free-ssl-let-s-encrypt-for-node-js-on-a-vps-ta548?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
