在VPS上安装VPN(如OpenVPN、WireGuard或IPSec/L2TP)可以让你安全地访问互联网或搭建私有网络,以下是常见VPN方案的安装指南:
OpenVPN(易用且功能丰富)
安装步骤(Ubuntu/Debian为例):
# 安装OpenVPN和Easy-RSA(证书工具) sudo apt install openvpn easy-rsa -y # 配置证书 make-cadir ~/openvpn-ca cd ~/openvpn-ca source vars ./clean-all ./build-ca # 生成CA证书(一路回车默认) ./build-key-server server # 生成服务器证书(Common Name填服务器IP或域名) ./build-key client1 # 生成客户端证书 ./build-dh # 生成Diffie-Hellman参数 openvpn --genkey --secret keys/ta.key # 生成TLS-auth密钥 # 复制文件到OpenVPN目录 cd ~/openvpn-ca/keys sudo cp server.crt server.key ca.crt dh2048.pem ta.key /etc/openvpn/ # 复制示例配置文件 gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz | sudo tee /etc/openvpn/server.conf # 编辑配置文件 sudo nano /etc/openvpn/server.conf
关键配置项:
proto udp(推荐)或proto tcpdev tunserver 10.8.0.0 255.255.255.0(VPN子网)push "redirect-gateway def1 bypass-dhcp"(客户端流量全走VPN)- 取消注释
tls-auth ta.key和dh dh2048.pem
启动OpenVPN:
sudo systemctl start openvpn@server sudo systemctl enable openvpn@server
生成客户端配置文件:
# 创建客户端配置(client1.ovpn) cat <<EOF > client1.ovpn client dev tun proto udp remote your_vps_ip 1194 resolv-retry infinite nobind persist-key persist-tun remote-cert-tls server cipher AES-256-CBC verb 3 <ca> $(cat ca.crt) </ca> <cert> $(cat client1.crt) </cert> <key> $(cat client1.key) </key> <tls-auth> $(cat ta.key) </tls-auth> key-direction 1 EOF
将生成的 client1.ovpn 文件下载到本地,用OpenVPN客户端导入即可连接。
WireGuard(高性能,现代协议)
安装步骤(Ubuntu/Debian):
# 安装WireGuard sudo apt install wireguard -y # 生成密钥对 wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey # 创建配置文件 sudo nano /etc/wireguard/wg0.conf
配置文件示例:
[Interface] PrivateKey = <服务器私钥(/etc/wireguard/privatekey内容)> Address = 10.0.0.1/24 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
启动WireGuard:
sudo systemctl enable --now wg-quick@wg0
客户端配置:
[Interface] PrivateKey = <客户端私钥> Address = 10.0.0.2/24 [Peer] PublicKey = <服务器公钥> Endpoint = your_vps_ip:51820 AllowedIPs = 0.0.0.0/0 PersistentKeepalive = 25
IPSec/L2TP(兼容性高,适合移动设备)
使用脚本快速安装(如Algo VPN):
git clone https://github.com/trailofbits/algo cd algo python3 -m pip install -r requirements.txt ./algo
按提示选择云提供商或本地部署,生成配置文件后导入设备即可。
注意事项
- 防火墙:开放VPN端口(如OpenVPN的1194/UDP,WireGuard的51820/UDP)。
sudo ufw allow 1194/udp sudo ufw enable
- 内核转发(如需流量转发):
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf sudo sysctl -p
- 日志检查:
journalctl -u openvpn@server或wg show。
根据需求选择方案:WireGuard适合高性能场景,OpenVPN功能更全面,IPSec/L2TP兼容旧设备。








