随着网站越来越容易遭遇攻击,单纯依靠防火墙和 Cloudflare WAF 已经不够。
Cloudflare Tunnel 提供了一种更安全的方式:它通过隧道连接,让你的网站源站不再暴露在公网,从而极大降低被攻击的风险。
本文将手把手教你在 VPS 上部署 Cloudflare Tunnel,保证 不影响现有的网站、应用和宝塔面板运行。
为什么选择 Cloudflare Tunnel?#
- 隐藏源站 IP:攻击者无法直接扫描你的服务器地址。
- 增强安全性:你可以直接关闭 80/443 公网端口。
- 兼容现有环境:不影响 Nginx/Apache、宝塔、数据库、应用运行。
- 更简单的架构:不必维护复杂的防火墙 IP 白名单。
一、安装 Cloudflare Tunnel#
Ubuntu / Debian#
`# 下载并安装
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared-linux-amd64.deb`
或者使用 apt(推荐)\#
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
echo ‘deb
https://pkg.cloudflare.com/cloudflared jammy main’ | sudo tee /etc/apt/sources.list.d/cloudflared.list
sudo apt update
sudo apt install cloudflared -y
CentOS / RHEL#
`sudo yum install https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-x86_64.rpm
`
二、认证登录#
`cloudflared tunnel login
`
运行后会打开浏览器,让你选择授权的域名。
三、创建 Tunnel#
`cloudflared tunnel create mywebsite
`
执行后会生成一个 Tunnel ID 和凭证文件,例如:
`/root/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json
`
请记住这个路径。
四、配置文件#
创建配置文件:
`sudo mkdir -p /etc/cloudflared
sudo nano /etc/cloudflared/config.yml
`
示例配置:
`tunnel: mywebsite
credentials-file: /root/.cloudflared/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.json`ingress:
– hostname: yourdomain.com
service: http://localhost:80– hostname: www.yourdomain.com\ service: http://localhost:80# 宝塔面板(可选)
– hostname: bt.yourdomain.com
service: https://localhost:8888
originRequest:
noTLSVerify: true
``# 其他应用(如 Node.js)
– hostname: app.yourdomain.com
service: http://localhost:3000
``# 默认规则
– service: http_status:404
五、配置 DNS#
为每个域名绑定到 Tunnel:
`cloudflared tunnel route dns mywebsite yourdomain.com
cloudflared tunnel route dns mywebsite www.yourdomain.com
cloudflared tunnel route dns mywebsite bt.yourdomain.com
`
六、测试运行#
`cloudflared tunnel --config /etc/cloudflared/config.yml run mywebsite
`
如果输出类似:
`INF Connection established
INF Started tunnel mywebsite
`
说明运行成功。
七、设置开机自启#
`sudo cloudflared service install
sudo systemctl enable cloudflared
sudo systemctl start cloudflared
sudo systemctl status cloudflared
`
八、安全加固(可选)#
既然隧道已经接管流量,可以关闭公网 80/443:
`sudo ufw deny 80
sudo ufw deny 443
sudo ufw allow 22 # SSH
sudo ufw allow 8888 # 本地宝塔面板
sudo ufw status
`
九、常见配置示例#
多站点#
`ingress:
- hostname: site1.com
service: http://localhost:80
originRequest:
httpHostHeader: site1.com`– hostname: site2.com
service: http://localhost:80
originRequest:
httpHostHeader: site2.com– hostname: api.site1.com\ service: http://localhost:3000– service: http_status:404
非标准端口#
`ingress:
- hostname: yourdomain.com
service: http://localhost:8080`– hostname: secure.yourdomain.com
service: https://localhost:8443
originRequest:
noTLSVerify: true``– service: http_status:404
十、故障排查#
`# 查看 Tunnel 信息
cloudflared tunnel info mywebsite`# 查看日志
sudo journalctl -u cloudflared -f# 验证配置文件\ cloudflared tunnel ingress validate# 重启服务
sudo systemctl restart cloudflared
十一、回滚方案#
如果不想用 Tunnel,恢复原状态也很简单:
`sudo systemctl stop cloudflared
sudo systemctl disable cloudflared`# Cloudflare 面板:把 DNS 记录改回 A 记录\
VPS 防火墙:重新开放 80/443\#
sudo ufw allow 80
sudo ufw allow 443
总结#
- Cloudflare Tunnel 完全不会影响你现有的网站和宝塔环境;
- 它的作用是隐藏源站 IP,让流量通过 Cloudflare 边缘节点转发;
- 配置成功后,你可以关闭公网 80/443,更加安全;
- 即使出问题,也可以随时回滚到原来的架构。
通过本文的教程,你就能让 VPS 网站获得企业级的防护能力,同时保持操作简单易懂。
其他VPS 安全加固方案:#
1. Cloudflare基础防护设置#
开启代理和基础防护#
# 在CF面板中:
- DNS记录设置为"代理"状态(橙色云朵)
- 安全级别设置为"Medium"或"High"
- 开启"Bot Fight Mode"
- 启用"Under Attack Mode"(受攻击时临时开启)WAF规则配置#
# Security -> WAF -> Custom rules
- 创建规则限制请求频率
- 阻止特定国家/地区访问
- 过滤恶意User-Agent
- 限制特定URI访问频率2. 服务器端配置#
防火墙设置(以Ubuntu为例)#
# 安装ufw防火墙
sudo ufw enable
# 只允许Cloudflare IP访问80/443端口
# 获取CF IP列表
curl https://www.cloudflare.com/ips-v4 > cf_ips.txt
curl https://www.cloudflare.com/ips-v6 >> cf_ips.txt
# 配置防火墙规则
sudo ufw deny 80
sudo ufw deny 443
# 允许CF IP段访问
while read ip; do
sudo ufw allow from $ip to any port 80
sudo ufw allow from $ip to any port 443
done < cf_ips.txt
# 允许SSH(改成你的端口)
sudo ufw allow 22/tcp安装fail2ban#
# 安装fail2ban
sudo apt install fail2ban
# 配置文件 /etc/fail2ban/jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
[sshd]
enabled = true
port = 22
maxretry = 3
[nginx-http-auth]
enabled = true
maxretry = 3
[nginx-noscript]
enabled = true
maxretry = 6
# 启动服务
sudo systemctl enable fail2ban
sudo systemctl start fail2ban3. Nginx安全配置#
基础安全配置#
# /etc/nginx/nginx.conf
http {
# 隐藏版本信息
server_tokens off;
# 限制请求大小
client_max_body_size 10M;
# 限制连接数
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}
server {
# 限制应用
limit_conn conn_limit_per_ip 10;
limit_req zone=req_limit_per_ip burst=10 nodelay;
# 只允许CF访问
allow 103.21.244.0/22;
allow 103.22.200.0/22;
# ... 其他CF IP段
deny all;
# 禁止访问敏感文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}4. 系统安全加固#
系统更新和安全设置#
# 自动更新
sudo apt update && sudo apt upgrade -y
# 安装安全工具
sudo apt install unattended-upgrades apt-listchanges
# 配置自动安全更新
sudo dpkg-reconfigure -plow unattended-upgrades
# 禁用root SSH登录
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
# 修改SSH端口
sudo sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config
# 重启SSH
sudo systemctl restart sshd安装入侵检测#
# 安装AIDE (文件完整性检查)
sudo apt install aide
# 初始化数据库
sudo aideinit
# 设置定期检查
echo "0 2 * * * /usr/bin/aide --check" | sudo crontab -5. 应用层防护#
如果使用WordPress#
// wp-config.php 安全配置
define('DISALLOW_FILE_EDIT', true);
define('WP_DEBUG', false);
define('FORCE_SSL_ADMIN', true);
// 限制登录尝试
// 安装插件: Limit Login Attempts Reloaded
如果使用自定义应用#
// PHP安全配置示例
<?php
// 输入过滤
function sanitize_input($data) {
return htmlspecialchars(strip_tags(trim($data)));
}
// SQL防注入 - 使用PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
// CSRF防护
session_start();
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die('CSRF token mismatch');
}
?>
6. 监控和日志#
设置监控脚本#
#!/bin/bash
# monitor.sh - 简单的监控脚本
# 检查CPU和内存
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
mem_usage=$(free | grep Mem | awk '{printf("%.2f"), $3/$2 * 100.0}')
# 检查磁盘空间
disk_usage=$(df -h / | awk 'NR==2{print $5}' | cut -d'%' -f1)
# 发送警报(如果超过阈值)
if [ $cpu_usage -gt 80 ] || [ $disk_usage -gt 90 ]; then
echo "High resource usage detected" | mail -s "Server Alert" your@email.com
fi
# 设置定时任务
# crontab -e
# */5 * * * * /path/to/monitor.sh7. 备份策略#
自动备份脚本#
#!/bin/bash
# backup.sh
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backup"
# 备份网站文件
tar -czf $BACKUP_DIR/website_$DATE.tar.gz /var/www/html/
# 备份数据库
mysqldump -u root -p[password] database_name > $BACKUP_DIR/db_$DATE.sql
# 删除7天前的备份
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete
find $BACKUP_DIR -name "*.sql" -mtime +7 -delete
# 上传到远程存储(可选)
# rsync -av $BACKUP_DIR/ user@remote-server:/backup/记住要根据你的具体环境调整这些配置,并且定期测试和更新安全设置。