WireGuard 安装与配置完整教程(服务器 + 客户端)

0
36

本教程将带你快速完成 WireGuard 的服务端与客户端配置,包括:

  • 服务端 wg0.conf 正确写法
  • 客户端配置示例(PC/iOS)
  • IP 转发与 NAT 设置
  • 全局代理与内网访问配置

适用于 Linux 服务器 + PC/iOS 客户端。


一、服务器端配置(wg0.conf)

以下示例是正确且推荐的服务端配置

[Interface]
Address = 192.168.6.1/24
PrivateKey = <服务器私钥>
ListenPort = 51820

[Peer]
PublicKey = <iOS 客户端公钥>
AllowedIPs = 192.168.6.2/32
PersistentKeepalive = 30  # iOS 建议开启

[Peer]
PublicKey = <PC 客户端公钥>
AllowedIPs = 192.168.6.3/32
PersistentKeepalive = 30  # PC 端可开启,避免 NAT 断连

⚠ 为什么服务端不写 Endpoint

  • WireGuard 服务器处于被动监听状态
  • 客户端连接后,服务器会自动学习客户端的公网 IP
  • 因此服务端 不需要也不应该写 Endpoint

只有当服务器作为客户端连接另一个 WG 节点时,才需要 Endpoint


二、PC 客户端配置(wg0.conf)

[Interface]
PrivateKey = <PC 客户端私钥>
Address = 192.168.6.3/24
DNS = 10.10.10.253

[Peer]
PublicKey = <服务器公钥>
AllowedIPs = 0.0.0.0/0     # 全局代理;仅访问内网可改为 192.168.6.0/24
Endpoint = a.b.com:51820
PersistentKeepalive = 30   # 避免 NAT 断连

✔ 客户端必须写 Endpoint

因为客户端需要知道服务器公网地址,否则无法连接。


三、开启服务器 IP 转发

如果客户端能上网但不能访问内网,通常是服务器未启用转发。

启用 IPv4 转发

echo "net.ipv4.ip_forward = 1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

启用 IPv6 转发(如使用)

echo "net.ipv6.conf.all.forwarding = 1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

四、服务器 NAT 设置(iptables)

若客户端访问不到内网设备(例如 192.168.6.0/24),需要为 WireGuard 设置 NAT 转换。

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i wg0 -o eth0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o wg0 -m state --state RELATED,ESTABLISHED -j ACCEPT

⚠ 请将 eth0 替换为你的真实网卡名称(运行 ip a 查看)。

永久保存规则

sudo apt install iptables-persistent
sudo netfilter-persistent save

五、支持全局代理 + 内网访问

如果希望客户端流量全部走 WireGuard,同时又能访问服务器内网设备,可使用下列写法:

[Peer]
AllowedIPs = 0.0.0.0/0, ::/0, 192.168.6.0/24

说明:

  • 0.0.0.0/0, ::/0 → 全部公网流量走 WireGuard
  • 192.168.6.0/24 → 用于访问服务器内网

📌 你的 WireGuard 已可正常工作!

按以上配置,基本可确保:

  • 服务端正确监听
  • 客户端稳定连接
  • 支持全局代理
  • 能访问服务端内网
  • 避免 NAT 断连

发布回复

请输入评论!
请输入你的名字