# SSH reverse tunnels (ssh -R), and when to stop doing it by hand

November 19, 2026, The Expose team

An SSH reverse tunnel, which the OpenSSH manual calls **remote port forwarding**, makes a port on a remote server lead back to a service on your machine. Your machine opens the SSH connection, so it works behind NAT, carrier-grade NAT and firewalls that block everything coming in. The traffic for the remote port then travels back inside that connection.

Run this on the machine behind the firewall:

```bash
ssh -N -R 8080:localhost:3000 user@server.example.com
```

While it runs, a connection to port 8080 on `server.example.com` reaches port 3000 on your machine. `-N` tells ssh not to start a shell, because you only want the forward.

Two things catch almost everyone out:

- **The remote port listens on `127.0.0.1` only.** Out of the box, only programs on the server itself can use it. To make it public you change `GatewayPorts` on the server, or put a reverse proxy in front. Both are covered below.
- **The tunnel dies quietly.** When your Wi-Fi drops or a NAT box forgets the connection, ssh can hang with the port still held on the server. You need keepalives and something that restarts it.

## How a reverse tunnel works

A firewall or NAT router stops connections coming in, but it lets connections go out. A reverse tunnel uses that. The machine you want to reach dials out to a server that has a public address, and the server sends incoming traffic back down the line:

```text
  your machine (behind NAT)                      server (public IP)

  ssh client --- 1. connects out to port 22 ---> sshd
     |                                           |
     |                                           +-- 2. listens on :8080 <-- 3. a visitor connects
     |                                           |
     <=========== 4. the traffic comes back =====+
     |            inside the same connection
     v
  app on localhost:3000
```

1. Your machine opens an ordinary outbound SSH connection to the server.
2. As part of it, ssh asks the server to listen on port 8080.
3. When something connects to port 8080, sshd passes that connection back through the SSH session.
4. The ssh client on your machine connects to `localhost:3000` and relays the data both ways.

It's "reverse" because the listening port is on the far end, not on your machine. Nothing ever has to reach your router from outside, so you don't need a public IP, router access or port forwarding. If you aren't sure why port forwarding fails on your connection, the [CGNAT check](https://expose.dev/cgnat-check) tells you whether your ISP puts you behind carrier-grade NAT.

## The ssh -R syntax

```text
ssh -N -R [bind_address:]remote_port:host:local_port user@server
```

| Part | What it means |
| --- | --- |
| `-N` | Don't run a remote command. Use it for a connection that only forwards ports. |
| `-R` | Remote port forwarding: the listening port is on the server. |
| `bind_address` | Optional. The interface on the server to listen on. Without it, the port listens on loopback only. `*` or an empty address means all interfaces, and only works if the server's `GatewayPorts` allows it. |
| `remote_port` | The port on the server. `0` asks the server to pick a free one. |
| `host:local_port` | Where your machine sends the traffic. ssh resolves `host` **on your side**, so it can be `localhost` or another machine on your network. |
| `user@server` | Your SSH login on the server. |

You can repeat `-R` to forward several ports over one connection. The forward lasts as long as the SSH connection: press Ctrl+C and the port on the server closes.

If you don't care which remote port you get, pass `0`. The server picks one and ssh prints it:

```console
$ ssh -N -R 0:localhost:3000 user@server.example.com
Allocated port 41235 for remote forward to localhost:3000
```

## Three worked examples

### 1. Open a local dev server from a VPS

Your app runs on `localhost:3000` on your laptop. You rent a small server at `vps.example.com`:

```bash
ssh -N -R 8080:localhost:3000 you@vps.example.com
```

Check it from the server, in a second terminal:

```bash
ssh you@vps.example.com 'curl -sI http://localhost:8080'
```

You get your app's response headers. Visitors on the internet can't reach port 8080 yet, because it listens on loopback. To publish it, either set [GatewayPorts](#make-the-port-public-gatewayports) or put [a reverse proxy with HTTPS](#put-https-in-front-instead) in front. The second is the better choice for anything a browser will open.

### 2. SSH into a Raspberry Pi behind CGNAT

The Pi sits on a network you can't forward ports on. Run this on the Pi:

```bash
ssh -N -R 2222:localhost:22 tunnel@vps.example.com
```

Port 2222 on the VPS now leads to the Pi's own SSH server. You don't need to make it public. Use the VPS as a jump host, and the connection to port 2222 starts on the VPS itself, where loopback is fine:

```bash
ssh -J you@vps.example.com -p 2222 pi@localhost
```

To save typing, add this to `~/.ssh/config` on your laptop and run `ssh pi`:

```text
Host pi
    HostName localhost
    Port 2222
    User pi
    ProxyJump you@vps.example.com
```

This is the classic use of a reverse tunnel, and the one where doing it by hand makes the most sense. To keep it up after reboots, see [keep the tunnel alive](#keep-the-tunnel-alive-keepalives-autossh-and-systemd).

### 3. Let a server reach a database on your network

A job on the VPS needs to read from a PostgreSQL server at `10.0.0.12` in your office network. Run this on any office machine that can reach the database:

```bash
ssh -N -R 15432:10.0.0.12:5432 you@vps.example.com
```

On the VPS, the job connects to `localhost:15432`. The office machine resolves `10.0.0.12` and opens the connection to the database. The database never has to accept a connection from outside the office network.

## Make the port public: GatewayPorts

By default, sshd binds every remote forward to the loopback address. The `GatewayPorts` setting in the server's `/etc/ssh/sshd_config` changes that:

| Value | What happens |
| --- | --- |
| `no` (default) | Remote forwards listen on `127.0.0.1` only, whatever the client asks for. |
| `yes` | Remote forwards listen on all interfaces, whatever the client asks for. |
| `clientspecified` | The client chooses with `bind_address`. Without one, the forward stays on loopback. |

Prefer `clientspecified`, and only for the account that runs tunnels. `yes` applies to every user and every forward on the server, including forwards that were meant to stay private. Create a separate account for tunnels, for example with `sudo adduser --disabled-password tunnel` on Debian and Ubuntu, and add this to the end of `/etc/ssh/sshd_config`, because a `Match` block applies until the next `Match` line or the end of the file:

```text
Match User tunnel
    AllowTcpForwarding remote
    GatewayPorts clientspecified
    PermitListen 8080 2222
    X11Forwarding no
    PermitTTY no
```

`AllowTcpForwarding remote` allows `-R` but not `-L`. `PermitListen` limits which ports the account may listen on, so a leaked key can't open anything else. Check the file and reload sshd:

```bash
sudo sshd -t
sudo systemctl reload ssh     # Debian and Ubuntu
sudo systemctl reload sshd    # Fedora, RHEL and most others
```

Now ask for all interfaces when you connect:

```bash
ssh -N -R 0.0.0.0:8080:localhost:3000 tunnel@vps.example.com
```

`0.0.0.0` binds IPv4 only. `'*:8080:localhost:3000'` binds every interface. Quote it, or your shell expands the `*`. On the server, `ss -tlnp | grep 8080` shows `0.0.0.0:8080` when it worked and `127.0.0.1:8080` when the setting isn't applied yet.

You can also tie a key to the tunnel with options in the tunnel user's `~/.ssh/authorized_keys`. `restrict` turns everything off, and the options after it allow back only what the tunnel needs:

```text
restrict,port-forwarding,permitlisten="8080" ssh-ed25519 AAAA... pi-tunnel
```

### What GatewayPorts exposes

Once the port listens on a public interface, the whole internet can connect to it. Think about what that means before you turn it on:

- **Your dev server faces scanners.** Debug pages, admin routes and test data become public at `http://your-server-ip:8080`.
- **The last hop is plain HTTP.** SSH encrypts the path between your machine and the server. From the visitor to the server, traffic travels unencrypted, passwords and cookies included.
- **The server's firewall has to allow the port,** in `ufw` or your cloud provider's firewall. Every port you open there stays open after the tunnel closes.

## Put HTTPS in front instead

For anything you'll open in a browser, leave `GatewayPorts` at `no` and run a reverse proxy on the server. The tunnel stays on `127.0.0.1:8080`, and the proxy serves it on a real hostname with a certificate. With [Caddy](https://caddyserver.com/docs/automatic-https), the whole config is:

```text
dev.example.com {
    reverse_proxy localhost:8080
}
```

Caddy gets and renews the certificate itself, as long as the domain's A or AAAA record points at the server and ports 80 and 443 are open. Nginx with Certbot works too, with more lines.

Each new tunnel needs its own port and its own site block. Routing many tunnels by hostname under one domain, such as `*.dev.example.com`, takes a wildcard certificate. Let's Encrypt only issues those through the [DNS-01 challenge](https://letsencrypt.org/docs/faq/), so your DNS provider has to support it.

Most dev servers check the `Host` header. Caddy passes the incoming `Host` header, here `dev.example.com`, through to your app unchanged, and Vite, webpack or Django may answer "Blocked request" or "Invalid Host header". [The fix for each framework](https://expose.dev/blog/invalid-host-header) is one line.

## Keep the tunnel alive: keepalives, autossh and systemd

An idle TCP connection through NAT can be dropped without either side noticing. ssh then sits there, and the server keeps holding port 8080 for a session that's gone. When you reconnect, you get:

```text
Warning: remote port forwarding failed for listen port 8080
```

ssh prints that warning and carries on without the forward. Three client options fix this:

```bash
ssh -N \
  -o ServerAliveInterval=15 \
  -o ServerAliveCountMax=3 \
  -o ExitOnForwardFailure=yes \
  -R 8080:localhost:3000 tunnel@vps.example.com
```

- **`ServerAliveInterval=15`** sends a keepalive through the encrypted channel after 15 seconds without data from the server.
- **`ServerAliveCountMax=3`** gives up after 3 unanswered keepalives. With these two values, ssh exits about 45 seconds after the server goes away, instead of hanging.
- **`ExitOnForwardFailure=yes`** makes ssh exit when it can't set up the forward, instead of running without it. A supervisor can then try again.

On the server, the matching sshd options free the port of a dead session. Add them to `sshd_config`, globally or in the `Match` block:

```text
ClientAliveInterval 15
ClientAliveCountMax 3
```

Rather than repeat the flags, put them in `~/.ssh/config` and run `ssh -N devtunnel`:

```text
Host devtunnel
    HostName vps.example.com
    User tunnel
    RemoteForward 8080 localhost:3000
    ServerAliveInterval 15
    ServerAliveCountMax 3
    ExitOnForwardFailure yes
```

### Run it in the background

For a quick session, `-f` sends ssh to the background. With `ExitOnForwardFailure`, it waits until the forward works before it does:

```bash
ssh -f -N -o ExitOnForwardFailure=yes -R 8080:localhost:3000 tunnel@vps.example.com
```

Nothing restarts it when it dies, though. For that, use autossh or systemd.

### autossh

[autossh](https://www.harding.motd.ca/autossh/) starts ssh and starts it again when it exits:

```bash
autossh -M 0 -N \
  -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes \
  -R 2222:localhost:22 tunnel@vps.example.com
```

`-M 0` turns off autossh's own monitoring port, so autossh only restarts ssh when it exits. The autossh README recommends the `ServerAlive` options for exactly this setup, because they make ssh exit when the server stops answering. One trap at boot: if the first connection fails within `AUTOSSH_GATETIME`, 30 seconds by default, autossh gives up. Set `AUTOSSH_GATETIME=0` if the network may not be up yet.

### systemd, without autossh

On a Linux machine you don't need autossh at all. systemd can restart plain ssh. First create a key without a passphrase for the tunnel:

```bash
ssh-keygen -t ed25519 -f ~/.ssh/tunnel_ed25519 -N ''
```

Add the contents of `~/.ssh/tunnel_ed25519.pub` to `~tunnel/.ssh/authorized_keys` on the server, ideally with the `restrict` options shown above and `permitlisten="2222"`. Then connect once by hand, as the user the service will run as, to accept the server's host key.

Then create `/etc/systemd/system/reverse-tunnel.service`:

```ini
[Unit]
Description=Reverse SSH tunnel to vps.example.com
After=network-online.target
Wants=network-online.target

[Service]
User=pi
ExecStart=/usr/bin/ssh -N -i /home/pi/.ssh/tunnel_ed25519 \
  -o BatchMode=yes \
  -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \
  -o ExitOnForwardFailure=yes \
  -R 2222:localhost:22 tunnel@vps.example.com
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

`BatchMode=yes` makes ssh fail instead of waiting for a password prompt nobody will answer. Start it, and enable it at boot:

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now reverse-tunnel
journalctl -u reverse-tunnel -f
```

## Local vs remote vs dynamic forwarding

ssh has three kinds of port forwarding. They differ in which side listens:

| | Local (`-L`) | Remote (`-R`) | Dynamic (`-D`) |
| --- | --- | --- | --- |
| Listens on | Your machine | The server | Your machine, as a SOCKS proxy |
| Connects to | A host and port, as seen from the server | A host and port, as seen from your machine | Whatever each app asks for, from the server |
| Use it to | Reach a service behind the server, such as a database | Make something behind your NAT reachable | Browse or connect through the server |
| Example | `ssh -N -L 5432:localhost:5432 user@db-host` | `ssh -N -R 8080:localhost:3000 user@vps` | `ssh -N -D 1080 user@vps` |
| Public listening controlled by | `-g`, or a bind address | `GatewayPorts` on the server | `-g`, or a bind address |

A quick way to remember it: `-L` brings a remote port to you, and `-R` sends one of your ports to the server.

## Common ssh -R problems

- **"remote port forwarding failed for listen port".** Something already uses the port on the server. Often that's your own dead session, which `ClientAliveInterval` clears. It can also mean the server refuses forwarding: check `AllowTcpForwarding` and `PermitListen`.
- **Ports below 1024.** Only a root login can forward privileged ports such as 80 or 443. Don't log in as root for this. Forward to 8080 and let a reverse proxy own 80 and 443.
- **It only works from the server itself.** The port is on `127.0.0.1`, because `GatewayPorts` is `no` or you left out the bind address. Check with `ss -tlnp`.
- **`-g` doesn't help.** It lets other hosts use your *local* forwards. For `-R`, only the server's `GatewayPorts` counts.
- **The port is public but nothing connects.** A firewall on the server or at your cloud provider is blocking it.
- **ssh can't get out at all.** Some office and guest networks block outgoing port 22. If nothing else on the server uses it, let sshd listen on 443 as well, with a second `Port 443` line.
- **The browser warns or refuses features.** The tunnel gives you plain HTTP. Browsers only allow the camera, the clipboard and service workers on HTTPS pages, and many OAuth providers only accept [HTTPS redirect URIs](https://expose.dev/docs/guides/oauth-callbacks). Put [HTTPS in front](#put-https-in-front-instead).
- **It works, then hangs after a while.** Add the keepalives above.

## When to stop doing it by hand

`ssh -R` gives you a raw TCP port on a server. Everything people expect from a tunnel URL, you add yourself, one piece at a time. Here is the ladder, and what each step adds:

| | What you run | What you get | What's still your job |
| --- | --- | --- | --- |
| **1. ssh -R to a VPS** | One ssh command, plus the VPS | A TCP port on a public IP | `GatewayPorts`, firewall, keepalives, restarts. Plain HTTP on `IP:port`. |
| **2. ssh -R plus a reverse proxy** | Caddy or Nginx on the VPS | HTTPS on a real hostname | A port and a site block per tunnel, DNS, certificates, keepalives |
| **3. Your own tunnel server** | The open-source Expose server on your VPS | A subdomain per tunnel, picked by the client, and a request dashboard on the client | The server, DNS, the TLS proxy, updates |
| **4. A hosted tunnel** | `expose share http://localhost:3000` | An HTTPS URL, the dashboard and replay | Nothing on a server |

### Step 3: run your own Expose server

Expose is a reverse tunnel too, built for HTTP. The [Expose server](https://expose.dev/docs/server/introduction) is open source ([github.com/exposedev/server](https://github.com/exposedev/server)), a PHP application you can run on the same VPS. It replaces one ssh port per app with routing by hostname. Each client asks for a subdomain, and the server sends requests for `my-app.my-domain.com` down the right connection.

[Starting the server](https://expose.dev/docs/server/server/starting-the-server) comes down to cloning the repository, running `composer install`, and:

```bash
expose-server serve my-domain.com --validateAuthTokens
```

The server listens on port 8080 by default. `--validateAuthTokens` lets only users with a token connect, and the admin interface at `expose.my-domain.com` manages those users and shows the connected sites. The same docs show how to keep the server running with supervisor, or with Docker. For HTTPS, you put Nginx, Apache, HAProxy or Caddy in front of it, as described in [SSL support](https://expose.dev/docs/server/server/ssl). Subdomains need a wildcard DNS record and a wildcard certificate, so the DNS challenge from step 2 still applies. The docs also recommend running it on port 443, so clients get through firewalls that block other ports.

What you gain over ssh: one DNS setup and one certificate cover every tunnel, clients choose a subdomain with `--subdomain`, and every client has the [request dashboard](https://expose.dev/docs/client/dashboard) at `http://127.0.0.1:4040`. It lists each request with its headers and body, and replays one without triggering it again, which helps a lot with webhooks. You still run the server.

### Step 4: a hosted tunnel

If you only need a dev server, a webhook endpoint or a demo online, you don't need a VPS at all:

```bash
expose share http://localhost:3000
```

![Terminal output of expose share showing the shared site, the dashboard URL, the public URL and incoming requests](https://expose.dev/img/docs/expose/img/expose_terminal.webp)

Expose prints a public HTTPS URL, and the dashboard with replay runs at `http://127.0.0.1:4040`. Visitors see your site directly, with no warning page in front of it, on every plan. Your app can keep listening on `127.0.0.1`. For a port that doesn't speak HTTP, such as SSH or a database, `expose share-port 22` shares a TCP port, which needs Pro.

The free plan gives you a random URL on each connection, one server in Frankfurt, and a time limit per connection. Expose Pro costs $79 per user per year and adds a [reserved subdomain](https://expose.dev/docs/expose-network/reserved-subdomains), so the URL stays the same when you reconnect, custom domains with one CNAME record, no time limit, and servers on five continents. The plans are in the [pricing section](https://expose.dev/#pricing).

ngrok also accepts a plain `ssh -R` instead of its agent, for example `ssh -R 443:localhost:80 v2@connect.ngrok-agent.com http`. Its [SSH reverse tunnel docs](https://ngrok.com/docs/gateway/agent/ssh-reverse-tunnel-agent) list what you give up: endpoints don't reconnect after a network interruption, and there's no traffic inspection. We checked that on November 19, 2026. For how the hosted tunnels compare, see [ngrok alternatives compared](https://expose.dev/alternatives).

### When raw ssh -R is the right answer

Stay with `ssh -R` and systemd when:

- **The tunnel has to run for months,** like SSH into a Raspberry Pi or a box at a customer's site. It's free if you already have a server, and nothing but your own setup decides how long it stays up. Expose is for development, demos and webhooks, and its free plan ends each connection after a time limit.
- **Your policy says traffic may only pass through servers you run.** Then use step 1, 2 or 3.
- **You need UDP.** Neither `ssh -R` nor Expose forwards UDP.

If only you need to reach your own devices, a mesh VPN does that without a public port. If the site has to stay up while your laptop is off, deploy it: [hosting from localhost](https://expose.dev/blog/hosting-localhost) compares a tunnel, [port forwarding on your router](https://expose.dev/blog/hosting-localhost#option-2-port-forwarding-on-your-router) and a deploy.

## Questions

### What is a reverse tunnel?

A reverse tunnel is a connection that a machine behind a firewall opens to an outside server, so that traffic arriving at the server can travel back to the machine. The machine connects out, and the traffic comes in. `ssh -R` builds one with SSH. Tunnel services such as Expose do the same for HTTP, and add a public URL and HTTPS.

### Is an SSH reverse tunnel secure?

The path between your machine and the server is encrypted and authenticated by SSH. The risk lies in what the server does with the port. On loopback, only users on the server can reach it. With `GatewayPorts`, anyone on the internet can, over plain HTTP unless you put HTTPS in front. Use a dedicated account, `PermitListen` or `permitlisten=`, and a key that can do nothing else.

### How do I run an SSH reverse tunnel in the background?

Use `ssh -f -N -o ExitOnForwardFailure=yes -R ...` for a one-off. For a tunnel that has to come back after a dropped connection or a reboot, run it as a systemd service with `Restart=always`, or under `autossh -M 0`.

### Can ssh -R forward UDP?

No. OpenSSH forwards TCP ports and Unix sockets. For UDP you need a VPN or a tunnel service that supports UDP.

### Do I need root on the server?

Not for ports 1024 and above. You need root, or someone who has it, to change `GatewayPorts` in `sshd_config`, to open the firewall, and to listen on ports below 1024.
