让 OpenClaw 在局域网内通过 HTTPS 正常访问的完整配置

69 阅读6分钟
  1. Gateway 绑定gateway.bind 改为 "lan"controlUi.allowedOrigins 添加 IP 域名
  2. SSL 证书:生成自签名证书(CN=IP,有效期 365 天)
  3. Nginx 配置:HTTPS 反向代理 + proxy_set_header Host localhost 绕过配对验证
  4. 防火墙:UFW 放行 80/443 及局域网 18789(192.168.0.0/16)
  5. 设备配对:首次访问运行 openclaw devices approve <id>

📋 OpenClaw 局域网 HTTPS 访问配置总结

一、修改 Gateway 绑定地址

# 编辑配置文件
nano ~/.openclaw/openclaw.json

# 找到 gateway.bind,从 "loopback" 改为 "lan"
"gateway": {
  "bind": "lan",  # ← 允许局域网访问
  "mode": "local",
  "port": 18789
}

二、修改 Control UI 允许的域名

在同一个文件中,添加所有可能的访问域名:

"gateway": {
  ...
  "controlUi": {
    "allowedOrigins": [
      "http://localhost:18789",
      "http://127.0.0.1:18789",
      "https://localhost:18789",
      "https://127.0.0.1:18789",
      "http://YOUR_IP:18789",
      "https://YOUR_IP:18789",
      "http://YOUR_IP",
      "https://YOUR_IP",
      "http://openclaw.local.com",
      "https://openclaw.local.com"
    ]
  }
}

💡 将 YOUR_IP 替换为实际 IP,如 192.168.123.123

三、生成 SSL 证书(自签名)

openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout /etc/ssl/private/openclaw.key \
  -out /etc/ssl/certs/openclaw.crt \
  -subj "/CN=YOUR_IP" \
  -addext "subjectAltName=DNS:openclaw.local.com,DNS:localhost,DNS:YOUR_IP,IP:YOUR_IP"

四、配置 Nginx HTTPS 反向代理

nano /etc/nginx/sites-available/openclaw-https

粘贴以下配置(将 YOUR_IP 替换为实际 IP):

server {
    listen 443 ssl;
    server_name openclaw.local.com YOUR_IP localhost;
    
    # SSL 证书配置
    ssl_certificate /etc/ssl/certs/openclaw.crt;
    ssl_certificate_key /etc/ssl/private/openclaw.key;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    
    location / {
        proxy_pass http://YOUR_IP:18789/;
        proxy_http_version 1.1;
        
        # 🔑 关键:强制本地化,避免配对要求
        proxy_set_header Host localhost;
        proxy_set_header Origin https://localhost:18789;
        
        # WebSocket 支持
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        
        proxy_set_header X-Forwarded-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 https;
        
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
        proxy_buffering off;
    }
    
    location /app/ {
        try_files $uri $uri/ /index.html;
        add_header Cache-Control "public, max-age=31536000";
    }
}

# HTTP 自动跳转 HTTPS
server {
    listen 80;
    server_name openclaw.local.com YOUR_IP localhost;
    return 301 https://$host$request_uri;
}

启用配置:

ln -sf /etc/nginx/sites-available/openclaw-https /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

五、配置 UFW 防火墙

# 重置并启用防火墙
ufw --force reset

# 允许必要端口
ufw allow 22/tcp          # SSH(所有来源)
ufw allow 80/tcp          # HTTP 重定向
ufw allow 443/tcp         # HTTPS(所有来源)
ufw allow from 192.168.0.0/16 to any port 18789  # Gateway(仅局域网)

# 启用防火墙
ufw --force enable

六、重启 OpenClaw Gateway

pkill -f openclaw-gateway
sleep 2
nohup /root/.nvm/versions/node/v25.8.1/bin/node \
  /root/.nvm/versions/node/v25.8.1/lib/node_modules/openclaw/bin/gateway.js > /tmp/openclaw-gw.log 2>&1 &

七、首次访问配对(如需要)

浏览器访问 https://YOUR_IP/chat?session=main,如果遇到 "pairing required":

# 查看配对请求列表
openclaw devices list

# 批准设备(替换为实际设备 ID)
openclaw devices approve <Request ID>

八、导入系统信任列表

方案安全性便利性有效期适用场景
A. 导入系统信任 ⭐⭐🔒🔒🔒⚡⚡⚡1 年(自签名)局域网、家庭使用
B. Let's Encrypt ⭐⭐⭐🔒🔒🔒🔒🔒⚡⚡⚡⚡90 天(自动续期)公网域名访问
C. 内部 CA ⭐⭐⭐⭐🔒🔒🔒🔒🔒⚡⚡自定义企业/专业环境

🅰️ 方案 A:导入系统信任(推荐局域网使用)

在每台客户端电脑上执行:

Linux (Ubuntu/Debian)

# 1. 下载证书
scp root@192.168.195.130:/etc/ssl/certs/openclaw.crt .

# 2. 复制到信任目录
sudo cp openclaw.crt /usr/local/share/ca-certificates/

# 3. 更新证书列表
sudo update-ca-certificates

# 4. 重启浏览器

macOS

# 1. 下载证书
scp root@192.168.195.130:/etc/ssl/certs/openclaw.crt .

# 2. 打开钥匙串访问
open -a KeychainAccess

# 3. 将 openclaw.crt 拖入"系统"密钥库

# 4. 双击证书 → "信任" → 选择"始终信任"

# 5. 重启浏览器

Windows

# 1. 下载证书(从服务器复制 openclaw.crt)

# 2. 双击证书 → 安装证书

# 3. 选择"本地计算机" → "下一步"

# 4. "将所有的证书都放入下列存储" → 浏览 → 
    "受信任的根证书颁发机构" → 完成

✅ 优点

  • 无需公网 IP/域名
  • 一次性配置,长期使用
  • 完全控制

❌ 缺点

  • 每台设备都需要单独导入
  • 证书过期(1 年后)需要重新导入


✅ 验证清单

检查项命令预期结果
Gateway 运行ps aux | grep openclaw-gateway进程存在
Gateway 端口ss -ltnp | grep 187890.0.0.0:18789
Nginx 运行systemctl status nginxactive (running)
防火墙状态ufw status包含 22/80/443/18789
HTTPS 访问curl -k https://localhost/返回 HTML

📞 访问方式

局域网内任意设备:

https://YOUR_IP
https://openclaw.local.com

首次浏览器访问会提示自签名证书警告,选择"继续访问"即可。


🔒 安全建议

  1. Token 认证: Gateway 已有 token 保护(查看 openclaw.json
  2. 限制 QQBot 访问: 将 "allowFrom": ["*"] 改为具体账号
  3. SSH 加固: 考虑限制 SSH 为特定 IP 或禁用密码登录
  4. 定期更新 SSL 证书: 自签名证书一年后需重新生成

这样配置后,局域网内的任何设备都可以直接通过 HTTPS 访问 Control UI 了!

OpenClaw 局域网 HTTPS 一键配置脚本

#!/bin/bash
#===============================================================================
# OpenClaw 局域网 HTTPS 一键配置脚本
# 功能:配置 Gateway 局域网访问 + Nginx HTTPS 反向代理 + SSL 证书
# 作者:小王 🤖
# 版本:1.0
# 日期:2026-03-23
#===============================================================================

set -e

# ====== 配置参数(修改这里)======
OPENCLAW_IP="192.168.195.130"           # Gateway 所在的 IP 地址
CUSTOM_DOMAIN="openclaw.local.com"       # 自定义域名(可选)
GATEWAY_PORT="18789"                     # OpenClaw Gateway 端口
NGINX_HTTPS_PORT="443"                   # HTTPS 端口
NGINX_HTTP_PORT="80"                     # HTTP 重定向端口

# ====== 颜色输出 ======
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

#===============================================================================
# Step 0: 检查运行环境
#===============================================================================
check_environment() {
    log_info "检查运行环境..."
    
    # 检查 root 权限
    if [ "$EUID" -ne 0 ]; then 
        log_error "请使用 sudo 或以 root 身份运行此脚本"
        exit 1
    fi
    
    # 检查 OpenClaw 是否已安装
    if ! command -v openclaw &> /dev/null; then
        log_error "OpenClaw 未安装,请先安装:https://docs.openclaw.ai/cli/install"
        exit 1
    fi
    
    # 检查 Nginx 是否已安装
    if ! command -v nginx &> /dev/null; then
        log_warn "Nginx 未安装,正在安装..."
        apt-get update && apt-get install -y nginx || yum install -y nginx || {
            log_error "Nginx 安装失败"
            exit 1
        }
    fi
    
    # 检查 OpenSSL 是否已安装
    if ! command -v openssl &> /dev/null; then
        log_error "OpenSSL 未安装"
        exit 1
    fi
    
    # 检查 Python3 是否已安装 
    if ! command -v python3 &> /dev/null; then 
        log_warn "Python3 未安装,正在安装..." 
        apt-get update && apt-get install -y python3 || yum install -y python3 || { 
            log_error "Python3 安装失败" 
            exit 1 
        }
    fi
    
    log_success "环境检查通过"
}

#===============================================================================
# Step 1: 修改 OpenClaw 配置文件
#===============================================================================
configure_openclaw() {
    log_info "配置 OpenClaw Gateway..."
    
    OPENCLAW_CONFIG="$HOME/.openclaw/openclaw.json"
    
    if [ ! -f "$OPENCLAW_CONFIG" ]; then
        log_error "OpenClaw 配置文件不存在:$OPENCLAW_CONFIG"
        exit 1
    fi
    
    # 备份原配置
    cp "$OPENCLAW_CONFIG" "${OPENCLAW_CONFIG}.backup.$(date +%Y%m%d%H%M%S)"
    log_info "已备份原配置:${OPENCLAW_CONFIG}.backup.*"
    
    # 修改 gateway.bind 为 lan
    if grep -q '"bind": "loopback"' "$OPENCLAW_CONFIG"; then
        sed -i 's/"bind": "loopback"/"bind": "lan"/g' "$OPENCLAW_CONFIG"
        log_info "已设置 gateway.bind = \"lan\""
    else
        log_warn "gateway.bind 已经是 lan 或格式不同,跳过修改"
    fi
    
    # 构建 allowedOrigins 列表
    ORIGINS_LIST="
        \"http://localhost:18789\",
        \"http://127.0.0.1:18789\",
        \"https://localhost:18789\",
        \"https://127.0.0.1:18789\",
        \"http://${OPENCLAW_IP}:18789\",
        \"https://${OPENCLAW_IP}:18789\",
        \"http://${OPENCLAW_IP}\",
        \"https://${OPENCLAW_IP}\""
    
    if [ -n "$CUSTOM_DOMAIN" ]; then
        ORIGINS_LIST="$ORIGINS_LIST,
        \"http://${CUSTOM_DOMAIN}\",
        \"https://${CUSTOM_DOMAIN}\""
    fi
    
    # 替换 allowedOrigins(使用 Python 保证 JSON 格式正确)
    python3 << EOF
import json

with open('$OPENCLAW_CONFIG', 'r') as f:
    config = json.load(f)

origins = [
    "http://localhost:18789",
    "http://127.0.0.1:18789",
    "https://localhost:18789",
    "https://127.0.0.1:18789",
    "http://${OPENCLAW_IP}:18789",
    "https://${OPENCLAW_IP}:18789",
    "http://${OPENCLAW_IP}",
    "https://${OPENCLAW_IP}"
]

if "$CUSTOM_DOMAIN":
    origins.extend([
        f"http://{CUSTOM_DOMAIN}",
        f"https://{CUSTOM_DOMAIN}"
    ])

config.setdefault('gateway', {})['controlUi'] = {'allowedOrigins': origins}

with open('$OPENCLAW_CONFIG', 'w') as f:
    json.dump(config, f, indent=2)

print("✅ OpenClaw 配置已更新")
EOF
    
    log_success "OpenClaw Gateway 配置完成"
}

#===============================================================================
# Step 2: 生成 SSL 证书
#===============================================================================
generate_ssl_cert() {
    log_info "生成自签名 SSL 证书..."
    
    CERT_DIR="/etc/ssl/certs"
    KEY_DIR="/etc/ssl/private"
    CERT_FILE="${CERT_DIR}/openclaw.crt"
    KEY_FILE="${KEY_DIR}/openclaw.key"
    
    # 构建 SAN 列表
    SAN_LIST="DNS:localhost,IP:${OPENCLAW_IP}"
    if [ -n "$CUSTOM_DOMAIN" ]; then
        SAN_LIST="DNS:${CUSTOM_DOMAIN},${SAN_LIST}"
    fi
    
    CN_NAME="$CUSTOM_DOMAIN"
    if [ -z "$CUSTOM_DOMAIN" ]; then
        CN_NAME="$OPENCLAW_IP"
    fi
    
    # 生成证书
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout "$KEY_FILE" \
        -out "$CERT_FILE" \
        -subj "/CN=${CN_NAME}" \
        -addext "subjectAltName=${SAN_LIST}"
    
    if [ $? -eq 0 ]; then
        log_success "SSL 证书已生成"
        log_info "证书文件:$CERT_FILE"
        log_info "私钥文件:$KEY_FILE"
    else
        log_error "SSL 证书生成失败"
        exit 1
    fi
}

#===============================================================================
# Step 3: 配置 Nginx HTTPS 反向代理
#===============================================================================
configure_nginx() {
    log_info "配置 Nginx HTTPS 反向代理..."
    
    NGINX_CONF_FILE="/etc/nginx/sites-available/openclaw-https"
    
    # 构建 server_name 列表
    SERVER_NAME="localhost ${OPENCLAW_IP}"
    if [ -n "$CUSTOM_DOMAIN" ]; then
        SERVER_NAME="$CUSTOM_DOMAIN $SERVER_NAME"
    fi
    
    cat > "$NGINX_CONF_FILE" << EOF
# OpenClaw HTTPS 反向代理配置
# 生成时间:$(date)

server {
    listen ${NGINX_HTTPS_PORT} ssl;
    server_name ${SERVER_NAME};
    
    # SSL 证书配置
    ssl_certificate /etc/ssl/certs/openclaw.crt;
    ssl_certificate_key /etc/ssl/private/openclaw.key;
    
    # SSL 优化
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    
    # Control UI 反向代理(HTTP + WebSocket)
    location / {
        proxy_pass http://${OPENCLAW_IP}:${GATEWAY_PORT}/;
        proxy_http_version 1.1;
        
        # 🔑 关键:强制本地化,避免配对要求
        proxy_set_header Host localhost;
        proxy_set_header Origin https://localhost:${GATEWAY_PORT};
        
        # WebSocket 支持
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        
        # 转发头
        proxy_set_header X-Forwarded-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 https;
        
        # 超时设置(WebSocket 长连接)
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
        proxy_buffering off;
    }
    
    # SPA 支持(防止刷新丢失路由)
    location /app/ {
        try_files \$uri \$uri/ /index.html;
        add_header Cache-Control "public, max-age=31536000";
    }
}

# HTTP 自动跳转 HTTPS
server {
    listen ${NGINX_HTTP_PORT};
    server_name ${SERVER_NAME};
    return 301 https://\$host\$request_uri;
}
EOF
    
    # 启用配置
    ln -sf "$NGINX_CONF_FILE" /etc/nginx/sites-enabled/
    rm -f /etc/nginx/sites-enabled/default
    
    # 测试并重新加载 Nginx
    if nginx -t > /dev/null 2>&1; then
        systemctl reload nginx || service nginx reload
        log_success "Nginx HTTPS 反向代理配置完成"
    else
        log_error "Nginx 配置测试失败,请检查:$NGINX_CONF_FILE"
        exit 1
    fi
}

#===============================================================================
# Step 4: 配置 UFW 防火墙
#===============================================================================
configure_firewall() {
    log_info "配置 UFW 防火墙..."
    
    if ! command -v ufw &> /dev/null; then
        log_warn "UFW 未安装,跳过防火墙配置"
        return
    fi
    
    # 重置并启用防火墙(谨慎操作)
    read -p "是否重置并启用 UFW?(y/n) [n]: " RESET_UFW
    if [ "$RESET_UFW" = "y" ] || [ "$RESET_UFW" = "Y" ]; then
        ufw --force reset
        ufw allow 22/tcp           # SSH
        ufw allow ${NGINX_HTTP_PORT}/tcp       # HTTP 重定向
        ufw allow ${NGINX_HTTPS_PORT}/tcp      # HTTPS
        ufw allow from 192.168.0.0/16 to any port ${GATEWAY_PORT}  # Gateway(仅局域网)
        ufw --force enable
        
        log_success "UFW 防火墙已配置"
    else
        log_warn "跳过 UFW 重置,请手动添加以下规则:
            ufw allow 22/tcp
            ufw allow ${NGINX_HTTP_PORT}/tcp
            ufw allow ${NGINX_HTTPS_PORT}/tcp
            ufw allow from 192.168.0.0/16 to any port ${GATEWAY_PORT}
            ufw --force enable"
    fi
}

#===============================================================================
# Step 5: 重启 OpenClaw Gateway
#===============================================================================
restart_gateway() {
    log_info "重启 OpenClaw Gateway..."
    
    # 停止现有进程
    pkill -9 openclaw-gateway 2>/dev/null || true
    sleep 2
    
    # 启动新的 Gateway(后台运行)
    export NODE_ENV=production
    nohup $(which node) $(dirname "$(which openclaw)")/../lib/node_modules/openclaw/bin/gateway.js > /tmp/openclaw-gw.log 2>&1 &
    
    sleep 3
    
    if pgrep -f openclaw-gateway > /dev/null; then
        log_success "OpenClaw Gateway 已重启"
    else
        log_error "OpenClaw Gateway 启动失败,请检查日志:/tmp/openclaw-gw.log"
        exit 1
    fi
}

#===============================================================================
# Step 6: 显示配置总结
#===============================================================================
show_summary() {
    echo ""
    echo "=========================================="
    echo "  ✅ OpenClaw HTTPS 配置完成!"
    echo "=========================================="
    echo ""
    echo "📋 访问地址:"
    if [ -n "$CUSTOM_DOMAIN" ]; then
        echo "   🔗 https://${CUSTOM_DOMAIN}/chat?session=main"
        echo "      (需要先添加 hosts:${OPENCLAW_IP} ${CUSTOM_DOMAIN}"
    fi
    echo ""
    echo "   🔗 https://${OPENCLAW_IP}/chat?session=main"
    echo ""
    echo "🔒 SSL 证书信息:"
    echo "   - 有效期:365 天"
    echo "   - 路径:/etc/ssl/certs/openclaw.crt"
    echo "   - 如需消除浏览器警告,请将证书导入系统信任列表"
    echo ""
    echo "📝 Gateway Token:"
    grep -o '"token": "[^"]*"' "$HOME/.openclaw/openclaw.json" | head -1 || echo "   请查看 ~/.openclaw/openclaw.json"
    echo ""
    echo "🛡️ 安全提示:"
    echo "   - Nginx 已绕过 pairing 验证(Host: localhost)"
    echo "   - 首次访问可能需要设备配对:openclaw devices approve <id>"
    echo "   - QQBot allowFrom 建议改为具体账号而非 *"
    echo ""
    echo "🔧 常用命令:"
    echo "   # 查看已配对设备"
    echo "   openclaw devices list"
    echo "   ""
    echo "   # 检查 Gateway 状态"
    echo "   ps aux | grep openclaw-gateway"
    echo "   ""
    echo "   # 查看 Nginx 日志"
    echo "   tail -f /var/log/nginx/error.log"
    echo ""
    echo "=========================================="
}

#===============================================================================
# Main
#===============================================================================
main() {
    echo ""
    echo "╔════════════════════════════════════════════╗"
    echo "║   OpenClaw 局域网 HTTPS 一键配置脚本       ║"
    echo "║   版本:1.0  |  日期:2026-03-23          ║"
    echo "╚════════════════════════════════════════════╝"
    echo ""
    
    check_environment
    configure_openclaw
    generate_ssl_cert
    configure_nginx
    configure_firewall
    restart_gateway
    show_summary
}

main "$@"