↓ 跳过正文

WireGuard 实现内网资源访问

正能量 2 分钟阅读 更新于 2026-10-18

补充 WireGuard 访问内网时的路由、AllowedIPs 与返回路径检查方法。

WireGuard 实现内网资源访问:原站配图。

通过 WireGuard 实现内网资源访问
#

场景描述
#

在企业或家庭网络中,常需要通过公网安全访问内部资源(如NAS、服务器、监控设备等)。WireGuard 凭借其轻量高效的特点,成为理想的VPN解决方案。

网络拓扑
#

公网客户端 <---> WireGuard Server(公网IP) <---> 内网资源(192.168.88.0/24)

配置步骤
#

1. 服务端准备
#

# Ubuntu/Debian 安装
sudo apt update && sudo apt install wireguard resolvconf -y

# 生成密钥对
umask 077
wg genkey | tee server_private.key | wg pubkey > server_public.key

2. 服务端配置
#

/etc/wireguard/wg0.conf

[Interface]
Address = 10.88.88.1/24
ListenPort = 1088
PrivateKey = <SERVER_PRIVATE_KEY>  # 替换为生成的私钥
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

# 客户端配置模板(每个客户端单独创建)
[Peer]
PublicKey = <CLIENT_PUBLIC_KEY>
AllowedIPs = 10.8.0.2/32  # 客户端分配的IP

3. 客户端配置
#

# 生成客户端密钥
wg genkey | tee client_private.key | wg pubkey > client_public.key

客户端配置文件

[Interface]
# WireGuard 接口的私钥,注意不要泄露这个私钥
PrivateKey = iF5rewTrFZSwH4iEfMOTC9Y9(不完整的私钥)
# 本地客户端的 IP 地址
Address = 10.88.88.24/16
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
[Peer]
# 服务器的公钥
PublicKey = aYRjKVpcXMeSBO/+w3amiJ0stZda0FR1wzJzUlcFmSs=
# 服务器的端点(IP 地址和端口)
Endpoint = xxxx.com:1088
# 允许的 IP 地址范围
AllowedIPs = 10.88.0.0/16,192.168.88.0/23
PersistentKeepalive = 25

4. 关键网络配置(客户端)
#

# 启用IP转发
echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-wireguard.conf
sudo sysctl -p

# 防火墙规则(UFW示例)
sudo ufw allow 51820/udp
sudo ufw allow from 10.8.0.0/24 to any port 22  # 示例规则

连接测试
#

# 查看连接状态
wg show

# 测试内网访问
ping 192.168.88.100
curl http://192.168.88.200:8080

高级配置技巧
#

  1. 多客户端管理:使用 wg set 动态添加客户端
  2. 移动端支持:使用QR码快速配置(qrencode -t ansiutf8 < client.conf)
  3. 安全增强:结合fail2ban防止暴力破解
  4. 性能优化:启用内核加速 wg-quick save /etc/wireguard/wg0.conf

故障排查
#

  • 服务端端口是否开放(nc -vzu <公网IP> 51820)
  • 路由是否正确(ip route show table all)
  • 密钥是否配对
  • MTU设置(可通过ping -s测试)

补充阅读
#

补充 WireGuard 访问内网时的路由、AllowedIPs 与返回路径检查方法。

如何理解与使用
#

握手成功说明对端能够通信,访问内网还需要目标网段路由、转发与合适的返回路径;先明确哪些地址应该经过隧道。

验证与边界
#

分别测试隧道地址、内网 IP、实际服务和域名解析,用分层结果定位问题。公私钥及内网网段需要按实际环境配置并保留恢复方式。