
# 命名隧道

默认情况下，Termbridge 使用 Cloudflare 的免账户 Quick Tunnel（`trycloudflare.com`）。使用方便，但频繁使用时可能会受到速率限制。

如果你经常使用 Termbridge，可以使用自己的 Cloudflare 账户设置命名隧道。

## 为什么使用命名隧道？

- **没有速率限制**：频繁使用 Quick Tunnel 时可能会返回 429 错误
- **稳定的 URL**：获得固定子域名，而不是随机字符串
- **自定义域名**：使用自己的域名，例如 `term.example.com`
- **更可靠**：命名隧道在长时间会话中更加稳定

## 设置

### 1. 创建 Cloudflare 账户

如果你还没有账户，请在 [cloudflare.com](https://cloudflare.com) 注册。

### 2. 在 Zero Trust 中创建隧道

1. 前往 [Cloudflare Zero Trust](https://one.dash.cloudflare.com/)
2. 前往 **Networks** → **Tunnels**
3. 点击 **Create a tunnel**
4. 选择 **Cloudflared** 作为连接器
5. 为隧道命名（例如 e.g、`termbridge`）
6. 复制隧道令牌

### 3. 添加公共主机名

1. 在隧道设置中，前往 **Public Hostname**
2. 添加一个指向 `http://localhost:8080` 的主机名（或指向你选择的端口）
3. 使用类似 `term.example.com` 的子域名

### 4. 使用令牌运行 Termbridge

```bash
termbridge --port 8080 --tunnel-token <TOKEN> --tunnel-url https://term.example.com
```

或使用环境变量：

```bash
export TERMBRIDGE_TUNNEL_TOKEN=<TOKEN>
export TERMBRIDGE_TUNNEL_URL=https://term.example.com

termbridge --port 8080
```

> **注意**
> 命名隧道必须使用 `--port` 标志，因为主机名已配置为指向特定端口。


## 配置选项

| 标志 | 环境变量 | 描述 |
|------|---------------------|-------------|
| `--port <port>` | - | 本地端口（命名隧道必填） |
| `--tunnel-token <token>` | `TERMBRIDGE_TUNNEL_TOKEN` | 你的隧道令牌 |
| `--tunnel-url <url>` | `TERMBRIDGE_TUNNEL_URL` | 你的公共主机名 URL |

## 完全禁用隧道

如果你有自己的反向代理或公共 URL：

```bash
termbridge --no-tunnel --public-url https://your-server.com
```

或者：

```bash
export TERMBRIDGE_TUNNEL=none
export TERMBRIDGE_PUBLIC_URL=https://your-server.com

termbridge
```

Termbridge 将跳过隧道启动，并在 QR 代码中使用你提供的 URL。

## 故障排除

### “429 Too Many Requests”

这表示 Quick Tunnel 受到速率限制。解决方法：

1. 等待几分钟后重试
2. 终止所有过期的 `cloudflared` 进程：`pkill cloudflared`
3. 切换到命名隧道（推荐）

### 隧道已启动，但 URL 无法使用

- 确认 Cloudflare 中的主机名与 `--tunnel-url` 一致
- 检查 Cloudflare 中的端口与 `--port` 一致
- 确保 cloudflared 是最新版本：`cloudflared update`

### 命名隧道无法连接

- 确认令牌正确
- 检查 Cloudflare Zero Trust 控制面板中是否有错误
- 尝试直接运行 `cloudflared tunnel run <TOKEN>` 以查看错误消息
