WireGuard VPN 快速配置
FreeGuideOnline
最新
2026-07-10
bash
更新软件包列表
sudo apt update
安装 WireGuard 核心工具
sudo apt install wireguard -y
如果使用较旧的发行版,可能需要添加 PPA 或启用 EPEL(CentOS/RHEL),请参考[官方文档](https://www.wireguard.com/install/)。
#### 开启 IP 转发
为使客户端能够通过服务器访问互联网,需要开启网络转发功能:
```bash
# 编辑系统控制文件
sudo nano /etc/sysctl.conf
找到 #net.ipv4.ip_forward=1 这行,取消注释(或直接新增一行):
net.ipv4.ip_forward=1
保存后,执行以下命令使配置立即生效:
sudo sysctl -p
生成密钥对
WireGuard 使用 Curve25519 密钥对进行身份认证,服务器和每个客户端都需要独立生成。
# 创建 WireGuard 配置目录并设置权限
sudo mkdir -p /etc/wireguard
cd /etc/wireguard
# 生成服务器私钥和公钥
wg genkey | sudo tee server_private.key | wg pubkey | sudo tee server_public.key
# 生成客户端私钥和公钥(示例中仅生成一对,生产中请为每个客户端单独生成)
wg genkey | sudo tee client_private.key | wg pubkey | sudo tee client_public.key
安全提示:私钥应严格保密,切勿泄露。本教程仅为演示方便将文件保存在
/etc/wireguard,生产环境建议妥善管理。
配置服务器
创建服务器配置文件 /etc/wireguard/wg0.conf:
sudo nano /etc/wireguard/wg0.conf
填入以下内容(请替换尖括号内为你实际的值):
[Interface]
Address = 10.0.0.1/24
PrivateKey = <服务器的私钥,可从 server_private.key 中获取>
ListenPort = 51820
# 服务器启动后自动添加 iptables 转发规则,让客户端共享服务器网络
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]
# 客户端 1 的配置
PublicKey = <客户端的公钥,可从 client_public.key 中获取>
AllowedIPs = 10.0.0.2/32
解释:
Address:服务器在 VPN 内网中的 IP,掩码/24表示可容纳 254 个客户端(10.0.0.2~10.0.0.254)。ListenPort:监听的 UDP 端口,确保已被防火墙放行。PostUp/PostDown:VPN 启动时自动设置 NAT 规则,关闭时清理。如果你的服务器主网口不是eth0,请改为实际名称(通过ip addr查看)。[Peer]段落添加每个允许接入的客户端,AllowedIPs指定该客户端在隧道内的 IP,建议按序分配以避免冲突。
配置客户端
以 Windows/macOS/Linux 桌面为例,配置文件内容如下(保存为 client.conf):
[Interface]
PrivateKey = <客户端的私钥,可从 client_private.key 中获取>
Address = 10.0.0.2/24
# 如果希望客户端所有的流量都走 VPN,可保留此行;若仅需访问内网,可删除
DNS = 8.8.8.8
[Peer]
PublicKey = <服务器的公钥,可从 server_public.key 中获取>
Endpoint = <你的服务器公网IP>:51820
AllowedIPs = 0.0.0.0/0, ::/0
# 若采用分流(仅内网流量走隧道),只需改为 VPN 子网:
# AllowedIPs = 10.0.0.0/24
PersistentKeepalive = 25
Address必须与服务器[Peer]中为该客户端指定的AllowedIPs一致。AllowedIPs决定了哪些目标 IP 的流量会进入隧道。0.0.0.0/0, ::/0表示全局代理;如果只想访问 VPN 内网,设为10.0.0.0/24即可。PersistentKeepalive保持 NAT 网络下的长连接,若服务器位于 NAT 之后,建议设置。
各平台导入方式
-
桌面端(Windows/macOS/Linux):安装官方客户端,点击“从文件导入隧道”,选择本例的
client.conf。 -
Android/iOS:应用商店安装 WireGuard,选择“从文件创建”或扫描配置二维码。
-
命令行 Linux:将配置文件复制到
/etc/wireguard/wg0-client.conf,然后执行:sudo wg-quick up wg0-client
启动服务器
在服务器上执行:
# 启动 wg0 接口
sudo wg-quick up wg0
# 设置开机自启
sudo systemctl enable wg-quick@wg0
查看隧道状态:
sudo wg show