最后更新于:2026年5月

VPS进阶优化
自建VPS CDN加速与负载均衡

自建VPS节点虽然灵活,但单点故障和速度波动是常见问题。本文介绍如何通过CDN加速和负载均衡提升自建节点的稳定性、速度和抗封锁能力。


🎯 为什么需要CDN加速?

单节点VPS的问题

常见问题:

解决方案:


CDN在代理中的应用

传统架构:

PLAINTEXT
用户 → 代理服务器 → 目标网站
       ↑
     单一IP(易封)

CDN加速架构:

PLAINTEXT
用户 → CDN边缘节点 → 代理服务器 → 目标网站
         ↓                ↑
      隐藏真实IP        多节点冗余

优势:


🌐 Cloudflare Workers 代理方案

为什么选择Cloudflare

优势:

免费额度:

PLAINTEXT
Workers:每天10万请求
Bandwidth:无限
KV存储:10万次写入/天

Workers 部署教程

步骤1:创建Workers

JAVASCRIPT
// worker.js
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  
  // 转发请求到你的VPS
  const proxyUrl = 'https://your-vps-domain.com' + url.pathname
  
  const proxyRequest = new Request(proxyUrl, {
    method: request.method,
    headers: request.headers,
    body: request.body,
    cf: { connectToApiToken: 'your-api-token' }
  })
  
  return fetch(proxyRequest)
}

步骤2:配置Wrangler

BASH
# 安装Wrangler
npm install -g wrangler

# 登录Cloudflare
wrangler login

# 创建项目
wrangler generate my-proxy worker.js
cd my-proxy

步骤3:部署

BASH
# 部署到Cloudflare
wrangler deploy

Workers + VPS 完整方案

架构设计:

PLAINTEXT
用户浏览器
    ↓
Cloudflare Workers(边缘代理)
    ↓
VPS源站(你的代理服务)
    ↓
目标网站

Workers代码优化:

JAVASCRIPT
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const url = new URL(request.url)
  
  // 支持路径路由
  let targetUrl
  
  if (url.pathname.startsWith('/proxy/')) {
    // 提取目标URL
    const target = atob(url.pathname.replace('/proxy/', ''))
    targetUrl = target + url.search
  } else {
    // 默认代理目标
    targetUrl = 'https://target-website.com'
  }
  
  // 构建代理请求
  const modifiedRequest = new Request(targetUrl, {
    method: request.method,
    headers: {
      ...request.headers,
      'X-Forwarded-For': request.headers.get('CF-Connecting-IP'),
      'X-Real-IP': request.headers.get('CF-Connecting-IP')
    },
    body: ['GET', 'HEAD'].includes(request.method) ? null : request.body
  })
  
  try {
    const response = await fetch(modifiedRequest)
    
    // 返回响应
    return new Response(response.body, {
      status: response.status,
      headers: response.headers
    })
  } catch (error) {
    return new Response('Proxy Error', { status: 502 })
  }
}

⚖️ 负载均衡配置

多节点负载均衡架构

架构图:

PLAINTEXT
用户请求
    ↓
负载均衡器(主)
    ↓
┌───┬───┬───┐
↓   ↓   ↓   ↓
V1  V2  V3  V4  ← VPS节点池
└───┴───┴───┘

方案对比:

方案 成本 复杂度 稳定性 性能
DNS轮询 免费 ⭐⭐⭐ ⭐⭐⭐
Cloudflare 免费 ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐
Nginx 免费 ⭐⭐⭐⭐ ⭐⭐⭐⭐
自建LB ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐

Cloudflare 负载均衡

步骤1:创建负载均衡器

BASH
# 使用Cloudflare API
curl -X POST "https://api.cloudflare.com/client/v4/loadbalancers" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "proxy-lb",
    "description": "Proxy Load Balancer",
    ".enabled": true,
    "fallback_pool": "fallback-pool-id",
    "default_pool_ids": ["pool-1-id", "pool-2-id"],
    "steering_policy": "dynamic_latency",
    "ttl": 30
  }'

步骤2:配置健康检查

JSON
{
  "health_check": {
    "path": "/health",
    "interval": 10,
    "timeout": 5,
    "retries": 3,
    "expected_body": "ok"
  }
}

步骤3:设置地理路由

JSON
{
  "steering_policy": "geo",
  "pop_access_rules": [
    {
      "type": "pop",
      "pop": "HKG",
      "pool": "hongkong-pool"
    },
    {
      "type": "pop", 
      "pop": "TKO",
      "pool": "tokyo-pool"
    },
    {
      "type": "pop",
      "pop": "LAX",
      "pool": "us-pool"
    }
  ]
}

Nginx 负载均衡

安装Nginx:

BASH
# Ubuntu/Debian
apt update && apt install nginx

# CentOS/RHEL
yum install nginx

配置负载均衡器:

NGINX
# /etc/nginx/conf.d/load-balancer.conf

# 上游VPS服务器池
upstream proxy_pool {
    # 最少连接(适合长连接)
    least_conn;
    
    # VPS节点
    server vps1.example.com:443 weight=5;
    server vps2.example.com:443 weight=3;
    server vps3.example.com:443 backup;
    
    # 健康检查
    keepalive 32;
}

# HTTP服务器
server {
    listen 80;
    server_name lb.example.com;
    
    location / {
        proxy_pass https://proxy_pool;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        # 连接复用
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        
        # 超时设置
        proxy_connect_timeout 10s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }
}

健康检查配置:

NGINX
# 添加健康检查路径
server {
    listen 80;
    server_name health.example.com;
    
    location / {
        return 200 'OK';
        add_header Content-Type text/plain;
    }
}

🔄 自动故障转移

健康检查脚本

Nginx + 上游健康检查:

BASH
#!/bin/bash
# health-check.sh

NODES=("vps1.example.com" "vps2.example.com" "vps3.example.com")
PORT=443
MAX_FAIL=3
CHECK_INTERVAL=10

while true; do
    for i in "${!NODES[@]}"; do
        NODE="${NODES[$i]}"
        
        # 检测节点状态
        if curl -s -o /dev/null -w "%{http_code}" \
            --connect-timeout 5 \
            "https://${NODE}:${PORT}/health" | grep -q "200"; then
            echo "$(date): ${NODE} is UP"
            # 节点恢复时的处理
        else
            echo "$(date): ${NODE} is DOWN"
            # 节点故障时的处理
        fi
    done
    
    sleep ${CHECK_INTERVAL}
done

自动切换脚本

BASH
#!/bin/bash
# failover.sh

# 当前活跃节点
CURRENT_NODE="vps1.example.com"
FAILOVER_NODE="vps2.example.com"

check_node() {
    local node=$1
    curl -s -o /dev/null --connect-timeout 5 \
        -w "%{http_code}" "https://${node}:443/health"
}

# 主节点故障,自动切换
if [ "$(check_node $CURRENT_NODE)" != "200" ]; then
    echo "主节点故障,切换到备用节点"
    
    # 更新Nginx配置
    sed -i "s/server $CURRENT_NODE/server $FAILOVER_NODE/g" \
        /etc/nginx/conf.d/load-balancer.conf
    
    # 重载Nginx
    nginx -s reload
    
    # 发送通知(可选)
    # curl -X POST "https://notify.example.com/alert" \
    #     -d "node=${CURRENT_NODE}&status=down"
fi

🚀 性能优化

TCP优化

服务器端优化:

BASH
# /etc/sysctl.conf

# BBR拥塞控制
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

# 连接优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535

# 内存优化
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216

# TCP快速打开
net.ipv4.tcp_fastopen = 3

# TIME_WAIT复用
net.ipv4.tcp_tw_reuse = 1

# 应用配置
sysctl -p

CDN缓存优化

Cloudflare缓存规则:

BASH
# 创建缓存规则
curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/rulesets/rules" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "phase": "http_request_cache_settings",
    "rules": [
      {
        "description": "Cache static content",
        "expression": "true",
        "action": "set_cache_settings",
        "action_parameters": {
          "cache": true,
          "edge_ttl": 86400,
          "origin_ttl": 604800
        }
      }
    ]
  }'

💰 成本优化

推荐配置方案

低成本方案(适合个人):

组件 推荐 成本
CDN Cloudflare免费版 $0
VPS×2 搬瓦工/HostDare $25-50/年
域名 .cf/.tk免费域名 $0
总计 $25-50/年

中等配置(适合小团队):

组件 推荐 成本
CDN Cloudflare Pro $20/月
VPS×4 各地优质线路 $10-20/节点/月
域名 .com $10/年
总计 $60-90/月

📊 监控与日志

Cloudflare Analytics

查看流量统计:

BASH
# 获取Workers使用量
curl -X GET "https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/workers/analytics/daily" \
  -H "Authorization: Bearer YOUR_TOKEN"

VPS监控脚本

BASH
#!/bin/bash
# monitor.sh

LOG_FILE="/var/log/vps-monitor.log"

# 监控指标
check_bandwidth() {
    vnstat --json | jq '.interfaces[0].traffic.total'
}

check_cpu() {
    top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1
}

check_memory() {
    free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)", $3,$2,$3*100/$2 }'
}

# 记录日志
echo "$(date): $(check_cpu) | $(check_memory)" >> $LOG_FILE

⚠️ 常见问题

Q: CDN加速会影响速度吗?

A:


Q: 免费CDN额度够用吗?

A:


Q: 负载均衡会增加延迟吗?

A:


Q: 如何防止CDN被滥用?

A:

  1. 设置访问频率限制
  2. 启用Cloudflare WAF
  3. 配置IP白名单
  4. 使用API Token而非API Key

总结

CDN加速方案总结

方案 适用场景 成本 难度
Cloudflare Workers 个人使用 免费 ⭐⭐
Cloudflare LB 小团队 $20/月 ⭐⭐⭐
Nginx LB 自建 免费 ⭐⭐⭐⭐
混合方案 企业 中高 ⭐⭐⭐⭐

最佳实践

CDN优先Cloudflare,免费额度充足
负载均衡至少2节点,避免单点故障
设置健康检查,自动故障转移
定期监控日志,及时发现问题
BGP优选,选择优质线路

最终建议:

👉 下一课: Amazon Prime Video区域解锁与内容对比

在下一课中,我们将对比全球Prime Video内容库,帮你解锁更多优质影视资源。

版权声明

作者: 易邦

链接: https://e8k.net/posts/vps-cdn-optimization/

许可证: 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。