# Nginx reverse proxy with free HTTPS using certbot

> An nginx reverse proxy receives requests on ports 80 and 443 and forwards them to your app on a local port, and certbot adds the HTTPS certificate.

URL: https://levelrail.com/learn/domains-https/nginx-reverse-proxy-with-certbot/
Updated: 2026-11-27

You have an app running on port 3000 and you want people to reach it at `https://example.com` with a padlock. Browsers expect ports 80 and 443, and your app should not handle certificates itself. Nginx sits in front, handles TLS and forwards plain HTTP to the app.

## How it works

A reverse proxy accepts the public connection and opens its own second connection to your app. The browser only ever talks to nginx. Nginx decides where to send each request using the `server_name` and `location` rules in its configuration.

Certbot gets the certificate by proving you control the domain. With the HTTP-01 method, Let's Encrypt asks for a small file at `http://example.com/.well-known/acme-challenge/...`. The nginx plugin serves that file for you, then edits your server block to listen on 443 with the certificate paths. This is why port 80 must be reachable from the internet, even if you only ever serve HTTPS afterwards.

After setup, nginx terminates TLS, so your app sees plain HTTP from `127.0.0.1`. The `proxy_set_header` lines pass along the original host, client IP and scheme so the app can still know them. Certificate files live under `/etc/letsencrypt/live/example.com/`.

DNS must be correct before certbot runs, and ports 80 and 443 must be open in the firewall and any cloud security group.

## Step 1: Install nginx

```bash
sudo apt update
sudo apt install nginx
```

What you should see: `systemctl status nginx` reports `active (running)`, and `http://203.0.113.10` shows the "Welcome to nginx" page.

## Step 2: Write the server block

Create `/etc/nginx/sites-available/example.com`:

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

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}
```

`listen [::]:80` also accepts IPv6. `proxy_pass` has no trailing slash or path, so the request path reaches the app unchanged.

## Step 3: Enable it and reload

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

`nginx -t` must report that the syntax is ok and the test is successful before you reload. A reload keeps serving old connections and only applies the new config if it is valid.

What you should see: `nginx: configuration file /etc/nginx/nginx.conf test is successful`, and `curl -I http://example.com` returns your app's response.

## Step 4: Install certbot

We use the snap method that certbot's site recommends:

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

What you should see: `certbot --version` prints a version number.

## Step 5: Get the certificate

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

`--nginx` uses the nginx plugin to prove ownership and edit the config. `-d` names the domain, and you can repeat it for `www.example.com`. Answer the prompts. Certbot edits the server block to listen on 443 and adds the certificate paths.

What you should see: a message that the certificate was successfully received and deployed, with its expiry date and the file paths.

## Check it worked

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

You should see an `HTTP/2 200` (or whatever your app returns) with no certificate error. Opening the site in a browser shows a padlock. Run `sudo nginx -t` once more and `sudo certbot renew --dry-run` to confirm renewal will work later.

## Edge cases and gotchas

- **The default site wins.** If you see "Welcome to nginx" on your domain, the request matched the default server. Check that `server_name` matches the exact host you typed, and remove `/etc/nginx/sites-enabled/default` if it is still there.
- **`proxy_pass` with a trailing slash changes the path.** `proxy_pass http://127.0.0.1:3000;` passes the path as is. `proxy_pass http://127.0.0.1:3000/;` strips the matched `location` prefix. Use one on purpose and test a nested URL.
- **Port 80 is taken.** Apache or another proxy may already hold port 80, and nginx logs `bind() to 0.0.0.0:80 failed (98: Address already in use)`. Find it with `sudo ss -tlnp` and stop it.
- **A Docker app with a published port bypasses the firewall.** `-p 3000:3000` binds to all addresses, and Docker adds its own rules ahead of ufw. Publish as `127.0.0.1:3000:3000` so only nginx reaches it.
- **Only the IPv4 record exists.** If you add an AAAA record that points nowhere useful, Let's Encrypt may try IPv6 and fail. Either serve IPv6 properly or remove the AAAA record.
- **Large uploads fail.** nginx limits request bodies by default, and a bigger upload returns 413. Raise `client_max_body_size` in the server block if your app takes uploads.
- **Websockets do not work.** They need `proxy_http_version 1.1;` plus `Upgrade` and `Connection` headers in the location block.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| Certbot says the challenge failed or timed out | DNS points elsewhere or port 80 is blocked | Fix the A record, open port 80 in firewall and cloud group |
| `502 Bad Gateway` | App is down or on another port | Check `ss -tlnp` and the nginx error log. See the 502 lesson |
| `connect() failed (111: Connection refused) while connecting to upstream` | Nothing listens on 127.0.0.1:3000 | Start the app or fix the port in `proxy_pass` |
| `bind() to 0.0.0.0:80 failed (98: Address already in use)` | Another process holds port 80 | Stop that process, then start nginx |
| `nginx -t` reports an error with a line number | Typo or missing semicolon | Fix the named file and line, test again |
| Browser shows the "Welcome to nginx" page | Default site matched instead | Match `server_name` and remove the default link |
| Mixed content or redirect loops in the app | App does not know the request was HTTPS | Keep `X-Forwarded-Proto` and make the app trust it |
| `504 Gateway Time-out` | App is slow, nginx gave up waiting | Fix the slow request, or raise `proxy_read_timeout` for that location |
| `413 Request Entity Too Large` | Upload bigger than `client_max_body_size` | Raise the limit in the server block, test, reload |
| Certbot cannot find a matching `server_name` | No server block lists the domain | Add `server_name example.com;` and reload before running certbot |

## Real-world scenario

You deploy a small Node app on a fresh VPS. It runs under [systemd](https://levelrail.com/learn/server-basics/run-a-service-with-systemd/)) on `127.0.0.1:3000`, and `curl http://127.0.0.1:3000` on the server works. The A record for `example.com` was set an hour ago.

You install nginx, write the server block from Step 2 and enable it. `sudo nginx -t` complains: the config test fails on a missing semicolon. You fix the line and test again. Then `curl -I http://example.com` returns the app's headers, so DNS and the proxy work.

You run `sudo certbot --nginx -d example.com -d www.example.com`. It fails on `www` because there is no A record for it. You add the record, wait for the resolver to catch up (check with `dig +short www.example.com @1.1.1.1`), and run certbot again. This time it succeeds and rewrites the server block. A last `sudo certbot renew --dry-run` passes.

A week later the app returns 502 after a reboot. nginx is fine. The app unit was not enabled at boot, so port 3000 had nothing listening. `sudo systemctl enable --now myapp` fixes it. For a step-by-step approach to that error see [fix 502 Bad Gateway](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)).

## Quick reference

```bash
sudo nginx -t                        # test config
sudo systemctl reload nginx          # apply it
sudo ss -tlnp | grep -E ':80|:443|:3000'   # who listens where
sudo certbot --nginx -d example.com  # issue and wire up
sudo certbot renew --dry-run         # test renewal
sudo tail -n 50 /var/log/nginx/error.log   # nginx errors
curl -I https://example.com          # end to end check
```

## Security and safety notes

- Never reload nginx before `nginx -t` passes.
- Do not expose the app port to the internet. Bind it to `127.0.0.1`.
- Back up `/etc/letsencrypt` if the server holds the only copy of account keys you rely on.

## Related lessons

- [What is a reverse proxy](https://levelrail.com/learn/deploy-operate/what-is-a-reverse-proxy/)): the idea behind the nginx setup.
- [Fix 502 Bad Gateway](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)): when nginx cannot reach the app.
- [Find what is using a port](https://levelrail.com/learn/server-basics/find-what-is-using-a-port/)): track down a port 80 conflict.

## Next

Certificates last about three months, so confirm they renew in [Renew Let's Encrypt certificates](https://levelrail.com/learn/domains-https/renew-lets-encrypt-certificates/)).

## Frequently asked questions

### Should I install certbot with snap or apt?

Certbot's own site recommends snap, so this lesson uses it. The apt package python3-certbot-nginx also works if you prefer to avoid snap.

### Why does certbot fail with a connection error?

Usually the domain does not point at the server yet, or port 80 is blocked by a firewall. Fix DNS and open ports 80 and 443, then run it again.

### Does my app need to know about HTTPS?

Not usually. nginx ends the TLS connection and talks plain HTTP to your app on localhost. Pass X-Forwarded-Proto so the app can tell the original request was HTTPS.

### Why bind the app to 127.0.0.1 and not 0.0.0.0?

On 127.0.0.1 only nginx on the same machine can reach it. On 0.0.0.0 anyone can hit port 3000 directly and skip HTTPS, and Docker-published ports can even bypass ufw rules.


## Sources

- [Certbot instructions](https://certbot.eff.org/instructions)
