搭建VPN服务端可以让你在远程访问私有网络资源或保护数据传输,以下是常见VPN协议的服务端搭建方法,包括 OpenVPN、WireGuard、IPSec/L2TP 等:
OpenVPN(跨平台,灵活)
Ubuntu/Debian 安装示例
sudo apt install openvpn easy-rsa # 2. 配置证书 make-cadir ~/openvpn-ca cd ~/openvpn-ca nano vars # 修改证书参数(如国家、组织等) source vars ./clean-all ./build-ca # 创建CA证书 ./build-key-server server # 创建服务器证书 ./build-key client1 # 创建客户端证书 ./build-dh # 生成Diffie-Hellman参数 # 3. 复制证书到OpenVPN目录 cd ~/openvpn-ca/keys sudo cp ca.crt server.crt server.key dh2048.pem /etc/openvpn # 4. 配置服务器 sudo cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/ sudo gzip -d /etc/openvpn/server.conf.gz sudo nano /etc/openvpn/server.conf # 检查以下关键配置: # proto udp # dev tun # ca ca.crt # cert server.crt # key server.key # dh dh2048.pem # server 10.8.0.0 255.255.255.0 # push "redirect-gateway def1" # 客户端流量全部走VPN # push "dhcp-option DNS 8.8.8.8" # 5. 启用IP转发和防火墙(NAT) sudo nano /etc/sysctl.conf # 取消注释 net.ipv4.ip_forward=1 sudo sysctl -p sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE sudo apt install iptables-persistent # 保存规则 # 6. 启动服务 sudo systemctl start openvpn@server sudo systemctl enable openvpn@server
客户端配置
将生成的 client1.crt、client1.key 和 ca.crt 复制到客户端设备,使用OpenVPN客户端导入。
WireGuard(高性能,轻量级)
Ubuntu/Debian 安装
# 1. 安装WireGuard sudo apt update sudo apt install wireguard resolvconf # 2. 生成密钥对 wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey # 3. 配置服务端(/etc/wireguard/wg0.conf) sudo nano /etc/wireguard/wg0.conf
配置文件示例:
[Interface] PrivateKey = <服务器私钥(来自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
启动服务
sudo systemctl enable wg-quick@wg0 sudo systemctl start wg-quick@wg0
客户端配置
客户端需生成自己的密钥对,并将服务端的 PublicKey 和 Endpoint 配置到客户端文件中。
IPSec/L2TP(兼容性好,适合移动设备)
使用 strongSwan 和 xl2tpd:
# 安装 sudo apt install strongswan xl2tpd # 配置IPSec(/etc/ipsec.conf)和L2TP(/etc/xl2tpd/xl2tpd.conf) # 需设置预共享密钥(PSK)和用户认证。
注意事项
-
安全性
- 使用强加密算法(如AES-256)。
- 定期更新证书和密钥。
- 限制VPN访问IP(通过防火墙)。
-
性能
- UDP协议(如OpenVPN/WireGuard)比TCP更快。
- WireGuard适合高吞吐量场景。
-
日志监控
- 检查日志:
journalctl -u openvpn@server或wg show。
- 检查日志:
-
合规性
确保遵守当地法律(某些国家限制VPN使用)。
选择建议
- 简单易用:WireGuard。
- 企业级兼容:OpenVPN或IPSec。
- 移动设备:IPSec/L2TP。
根据需求选择协议,并确保服务器防火墙开放对应端口(如UDP 1194 for OpenVPN)。









