准备工作
- 一台VPS(推荐Ubuntu/Debian/CentOS等Linux系统)。
- SSH访问权限(使用
root或具有sudo权限的用户)。 - 确保防火墙开放所需端口(默认UDP 51820用于WireGuard)。
安装WireGuard
Ubuntu/Debian
sudo apt update && sudo apt install -y wireguard resolvconf
CentOS/RHEL
sudo yum install -y epel-release && sudo yum install -y wireguard-tools
生成密钥对
cd /etc/wireguard umask 077 # 确保密钥文件权限安全 wg genkey | tee privatekey | wg pubkey > publickey
配置服务端
创建配置文件 /etc/wireguard/wg0.conf:
[Interface] PrivateKey = <服务器私钥(privatekey文件内容)> Address = 10.0.0.1/24 # 服务器虚拟IP ListenPort = 51820 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 = <客户端公钥> AllowedIPs = 10.0.0.2/32 # 客户端虚拟IP
- 替换
<服务器私钥>和<客户端公钥>。 eth0需改为你的实际网卡名(通过ip a查看)。
启动WireGuard
sudo systemctl enable --now wg-quick@wg0 sudo wg show # 查看运行状态
配置客户端
客户端(如手机/电脑)需安装WireGuard,并创建类似配置:
[Interface] PrivateKey = <客户端私钥> Address = 10.0.0.2/24 DNS = 8.8.8.8 # 可选,设置DNS [Peer] PublicKey = <服务器公钥> Endpoint = <服务器IP>:51820 AllowedIPs = 0.0.0.0/0 # 全局流量走VPN PersistentKeepalive = 25
防火墙设置
允许UDP端口(以UFW为例):
sudo ufw allow 51820/udp sudo ufw enable
测试连接
- 客户端连接后,通过
ping 10.0.0.1测试服务器连通性。 - 检查外网IP是否变为VPS的IP(访问
ifconfig.me)。
可选优化
- 多用户配置:为每个客户端添加独立的
[Peer]段。 - IPv4转发(需启用内核转发):
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf sudo sysctl -p
其他方案
- OpenVPN:使用
easy-rsa生成证书,配置稍复杂但兼容性更好。 - Shadowsocks:适合绕过网络审查(非传统VPN)。
根据需求选择协议,WireGuard适合高性能场景,OpenVPN更通用。








京公网安备11000000000001号
京ICP备11000001号