构建VPN(虚拟专用网络)通常涉及选择协议、配置服务器和客户端,并确保安全性和隐私,以下是详细步骤:
选择VPN协议
根据需求选择协议,常见选项:
- OpenVPN:开源、灵活,适合大多数场景(UDP/TCP端口)。
- WireGuard:高性能、轻量级,现代加密(UDP 51820)。
- IPSec/L2TP:兼容性好,但配置复杂(UDP 500/4500)。
- IKEv2:适合移动设备,自动重连(UDP 500)。
准备服务器
A. 购买VPS
- 推荐提供商:AWS Lightsail、DigitalOcean、Linode或阿里云。
- 选择靠近用户的地区,安装Linux系统(如Ubuntu 22.04)。
B. 基础配置
ssh root@your_server_ip apt update && apt upgrade -y
安装和配置VPN
OpenVPN
-
安装OpenVPN & Easy-RSA:
wget https://git.io/vpn -O openvpn-install.sh chmod +x openvpn-install.sh sudo ./openvpn-install.sh
脚本会提示输入配置(如IP、端口、DNS),按需选择。
-
生成客户端配置:
- 脚本会在
/root/生成.ovpn文件,下载到本地使用。
- 脚本会在
WireGuard
-
安装WireGuard:
apt install wireguard resolvconf -y
-
生成密钥对:
wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey
-
配置服务端(
/etc/wireguard/wg0.conf):[Interface] PrivateKey = <服务器私钥> Address = 10.8.0.1/24 ListenPort = 51820 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 = <客户端公钥> AllowedIPs = 10.8.0.2/32
-
启动WireGuard:
wg-quick up wg0 systemctl enable wg-quick@wg0
配置客户端
-
OpenVPN:使用
client.ovpn文件导入客户端软件(如OpenVPN Connect)。 -
WireGuard:创建客户端配置(示例):
[Interface] PrivateKey = <客户端私钥> Address = 10.8.0.2/24 DNS = 8.8.8.8 [Peer] PublicKey = <服务器公钥> Endpoint = your_server_ip:51820 AllowedIPs = 0.0.0.0/0 PersistentKeepalive = 25
防火墙和路由
ufw enable # 启用IP转发(WireGuard需NAT): echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf sysctl -p
测试连接
- 客户端连接后,检查IP是否变更(如访问ipleak.net)。
- 服务器端验证:
wg show # WireGuard cat /var/log/syslog | grep openvpn # OpenVPN
高级优化
- 安全性:禁用密码认证,仅使用密钥;启用TLS加密。
- 性能:调整MTU值(如
1420for WireGuard)。 - 多设备:为每个客户端生成独立配置。
注意事项
- 合规性:确保VPN使用符合当地法律。
- 日志管理:关闭无关日志以保护隐私。
- 备用方案:部署故障转移服务器(如使用Algo VPN脚本)。
如果需要更简单的部署,可考虑现成解决方案如Outline VPN或商业服务(Tailscale)。









