boxmoe_header_banner_img

Hello! 欢迎来到阿虪的开发世界~

加载中

文章导读

反代与 IP 实战指南:免费 Token 玩法下卷(Cloudflare Workers / Nginx / Caddy)


avatar
阿虪 18 10 月, 2026 186

本文转载自 linux.do 社区干货帖(免费 Token 玩法·下卷),接上卷补全反代与 IP 这块:反代 IP 被封、OpenAI 拒国内 IP、中转站跑路这些坑,一次讲透。

中文版

很多人卡在”反代 IP 被封”、”OpenAI 拒国内 IP”、”中转站跑路”这些坑上,这帖专门开一帖讲透。

一、为什么需要反代

OpenAI / Claude / Gemini 等海外 API:

  • 拒绝国内 IP 直连(OpenAI 直接返回 “Country not supported”)
  • 申请 Key 时检测出口 IP,国内 IP 直接 ban 账号
  • 国内 VPS 调用也会被拒(出口是 CN)

解决方案就两条路:A. 用中转站(chatanywhere、硅基流动这种)——他们的服务器在境外,替你转发;B. 自建反代——自己买境外 VPS 当中转。

二、IP 被封的几种原因

  • 出口 IP 是国内 → 申请 Key 直接被拒
  • VPS IP 段被 OpenAI 标记(很多廉价 VPS IP 段已被拉黑名单)
  • 同一 IP 多账号申请 → 关联封禁
  • IP 在 GFW 重点监控段 → 国内访问就被拦
  • 中转站 IP 被目标站风控 → 调用失败但余额扣了

判断 IP 干不干净:

  • curl https://api.openai.com/cdn-cgi/trace 看 loc 字段,是 US 就行,是 CN 就不行
  • 浏览器打开 https://ipinfo.io,看 country / ASN / 是否标 VPN / 是否在黑名单

危险 IP 段:搬瓦工 DC9 / CN2 GIA 部分段、阿里云国际 / 腾讯云国际 IP 段、Vultr 部分段被标记;干净 IP 推荐:Oracle Cloud Free Tier(美区 Phoenix / Ashburn)、AWS LightSail 美区($3.5/月)、Cloudflare Workers(Cloudflare 自家 IP,最干净)、Hetzner / Contabo 欧洲段。

三、反代方案 1:Cloudflare Workers(零成本,最推荐)

原理:用 Cloudflare 的边缘节点反代目标 API,IP 是 Cloudflare 的,全球干净。免费额度 10 万次/天。优点:零成本、IP 干净、全球 CDN;缺点:单次请求 10s 上限,长 streaming 会断。

部署步骤:1. 注册 Cloudflare 账号(免费);2. Dashboard → Workers & Pages → Create Worker;3. 粘贴下面代码:

export default {
  async fetch(req) {
    const url = new URL(req.url);
    const target = "https://api.openai.com" + url.pathname + url.search;
    const newReq = new Request(target, req);
    newReq.headers.set("Host", "api.openai.com");
    return fetch(newReq);
  }
}

部署后拿到 https://你的子域.workers.dev,调用时 Base URL 换成它:

from openai import OpenAI
client = OpenAI(
    api_key="sk-xxx",
    base_url="https://你的子域.workers.dev/v1"
)

Cline / Cursor / LobeChat 配置同理。进阶:Workers → Triggers → Custom Domains 绑自定义域名(域名需在 Cloudflare DNS),好处是 workers.dev 在国内有时被 Q,自定义域名不会。

四、反代方案 2:境外 VPS + Nginx(最稳,适合重度)

需要一台境外 VPS(Oracle Free / LightSail / Contabo)。优点:稳定、长连接、不限次数;缺点:要花时间配,VPS 可能要钱。

SSH 到 VPS:apt install nginx -y,配置 /etc/nginx/conf.d/api-proxy.conf:

server {
  listen 443 ssl;
  server_name api.你的域名.com;

  ssl_certificate     /path/to/cert.pem;
  ssl_certificate_key /path/to/key.pem;

  location / {
      proxy_pass https://api.openai.com;
      proxy_ssl_server_name on;
      proxy_set_header Host api.openai.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_buffering off;  # 重要:streaming 必须 off
      proxy_read_timeout 300s;
  }
}

免费证书:apt install certbot python3-certbot-nginx,certbot --nginx -d api.你的域名.com。

测试:curl https://api.你的域名.com/v1/models -H "Authorization: Bearer sk-xxx"。

反代多个 API(一个域名带前缀):

location /openai/ {
    proxy_pass https://api.openai.com/;
    proxy_set_header Host api.openai.com;
    proxy_buffering off;
}
location /claude/ {
    proxy_pass https://api.anthropic.com/;
    proxy_set_header Host api.anthropic.com;
    proxy_buffering off;
}
location /gemini/ {
    proxy_pass https://generativelanguage.googleapis.com/;
    proxy_set_header Host generativelanguage.googleapis.com;
    proxy_buffering off;
}

调用:OpenAI → https://api.你的域名.com/openai/v1;Claude → .../claude/v1;Gemini → .../gemini/v1beta。

五、反代方案 3:Caddy(最省事,自动 HTTPS)

比 nginx 简单 10 倍,自动申请 Let’s Encrypt 证书。安装 apt install caddy -y,配置 /etc/caddy/Caddyfile:

api.你的域名.com {
  reverse_proxy https://api.openai.com {
    header_up Host api.openai.com
  }
}

systemctl restart caddy 完事,自动申请证书 + 反代,3 行配置搞定。

六、反代方案 4:Cloudflare Tunnel(不用 VPS)

原理:在你本地机器跑 cloudflared,把本地服务暴露到公网。优点:不用买 VPS,不用配证书;缺点:依赖 Cloudflare 服务。

  1. 本机装 cloudflared:Windows 用 winget install cloudflare.cloudflared,Linux 用 apt install cloudflared
  2. 启动本地 OpenAI 兼容服务(比如 ollama serve)
  3. 创建 tunnel:cloudflared tunnel create myapi
  4. 配置 ~/.cloudflared/config.yml:tunnel 填 tunnel-id,ingress 里 hostname api.你的域名.com → http://localhost:11434
  5. 绑定 DNS:cloudflared tunnel route dns myapi api.你的域名.com
  6. 启动:cloudflared tunnel run myapi

七、中转站 IP 问题(用中转站的必须知道)

中转站的本质:你 → 中转站服务器 → OpenAI,中转站的出口 IP 是固定的,被 OpenAI 风控就全挂。常见坑:

  • 余额不退——站跑路或被封,钱打水漂
  • 偷偷降级——你以为调 GPT-4o,实际给你 GPT-4o-mini
  • 日志全留——你的 prompt、key、IP 全被中转站记录
  • IP 被风控——中转站 IP 被拉黑后所有用户一起挂
  • 价格戏法——标价便宜但偷偷加水(input/output 比例不正常)

验证中转站是否真调到原模型:prompt 写”不要回复任何内容,只输出你的 model_id”,真 GPT-4o 会输出 gpt-4o;或者问”1+1=2 吗?回答 yes 或 no 即可”,真模型答 yes。

中转站选用建议:别一次充超过 50 元,用完再充;优先选有 Discord / Telegram 群的(活的);查 GitHub issues 看最近有没有跑路迹象;别用中转站调敏感 prompt。

八、反代 IP 被封的解法

症状:突然所有请求返回 403 / “Country not supported”。解法:

  • 换 IP:VPS 控制台重启 / 换弹性 IP;Oracle Free 保留 Boot Volume 新建 VM 拿新 IP;LightSail Static IP 解绑再绑
  • 套 Cloudflare:VPS 反代前面再套一层 Cloudflare CDN,出口 IP 变成 Cloudflare
  • IP 池:买多个 VPS,nginx upstream 轮询
  • 住宅代理(Bright Data / IPRoyal):出口是住宅 IP,几乎不被封,缺点是按 GB 计费贵

九、反代注意事项

  • proxy_buffering off 是 streaming 必须的,不然 SSE 会被缓存
  • proxy_read_timeout 至少 300s
  • Host header 必须设对:OpenAI → api.openai.com;Claude → api.anthropic.com;Gemini → generativelanguage.googleapis.com;DeepSeek → api.deepseek.com
  • 别记 access log(保护 prompt 隐私):access_log off;
  • 加 rate limit 防滥用:limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

十、反代 + 鉴权(防被白嫖)

反代公开 URL 一定要加鉴权,否则被白嫖 + 被风控双杀。nginx 方案:

map $http_authorization $auth_ok {
  default 0;
  "Bearer 你的密钥" 1;
}
server {
  ...
  if ($auth_ok = 0) { return 401; }
}

或更简单:用 URL 路径当密钥:location /你的随机字符串/ { proxy_pass https://api.openai.com/; },访问 https://api.你的域名.com/你的随机字符串/v1/chat/completions。

十一、实战:多源 fallback 反代

场景:OpenAI 挂了自动切 Claude,Claude 挂了切 Gemini,用 OpenResty + Lua:

server {
  location /v1/chat/completions {
    access_by_lua_block {
      local sources = {"openai", "claude"}
      for _, src in ipairs(sources) do
        local res = ngx.location.capture("/proxy_" .. src,
          {method=ngx.HTTP_POST, body=ngx.req.get_body_data()})
        if res.status == 200 then
          ngx.say(res.body)
          ngx.exit(200)
        end
      end
      ngx.exit(500)
    }
  }
  location /proxy_openai {
    proxy_pass https://openai/v1/chat/completions;
    proxy_set_header Host api.openai.com;
  }
  location /proxy_claude {
    proxy_pass https://claude/v1/messages;
    proxy_set_header Host api.anthropic.com;
  }
}

十二、IP 隐藏层级(从弱到强)

L0 直连(源 IP 暴露)→ L1 HTTP 代理 → L2 HTTPS 代理 → L3 SOCKS5 代理 → L4 VPN → L5 VPN + 浏览器指纹伪装 → L6 住宅代理 + 指纹浏览器 → L7 多跳链路。调 API 最低要求 L3(SOCKS5 出口在境外);被风控后用 L5+;极端情况 L7。

十三、OpenAI 注册 IP 黑名单速查

大概率被拒:阿里云国际(47.x / 39.x)、腾讯云国际、华为云国际、部分 Vultr 段(108.x / 45.x)、部分 DigitalOcean 段、搬瓦工 DC9 CN2 GIA 部分。干净:Cloudflare Workers、Oracle Free Tier、AWS LightSail、Hetzner(欧洲)、Azure 美区。

十四、反代常见报错速查

  • 403 Country not supported → IP 被拒,换 IP
  • 401 Unauthorized → key 错或 header 没传对
  • 429 Too Many Requests → 限频,加 sleep 或换号
  • 502 Bad Gateway → 反代后端挂了
  • SSL_ERROR → 证书问题或 SNI 没设对
  • “stream disconnected” → proxy_buffering 没关
  • “Host header mismatch” → proxy_set_header Host 没设对
  • 调用很慢 → 没加 proxy_http_version 1.1; + proxy_set_header Connection "";

十五、完整反代 nginx 配置(抄就能用)

server {
  listen 443 ssl http2;
  server_name api.yours.com;

  ssl_certificate     /etc/letsencrypt/live/api.yours.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/api.yours.com/privkey.pem;

  access_log off;  # 关 access log 保护隐私
  error_log /var/log/nginx/api_error.log;

  proxy_read_timeout 600s;
  proxy_send_timeout 600s;

  limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;
  limit_req zone=api burst=10 nodelay;

  location / {
      proxy_pass https://api.openai.com;
      proxy_ssl_server_name on;
      proxy_set_header Host api.openai.com;
      proxy_set_header X-Real-IP "";
      proxy_set_header X-Forwarded-For "";
      proxy_http_version 1.1;
      proxy_set_header Connection "";
      proxy_buffering off;
      proxy_cache off;
      chunked_transfer_encoding on;
  }
}
server {
  listen 80;
  server_name api.yours.com;
  return 301 https://$server_name$request_uri;
}

部署:certbot --nginx -d api.yours.com,nginx -t && systemctl reload nginx。

十六、自建反代 vs 中转站对比

自建反代:+ 完全控制、无日志风险、不限次数(受限 VPS 带宽)、多 API 统一入口;- 需要 VPS($3.5+/月,Oracle Free 免费)、要配 nginx/caddy、要维护。中转站:+ 零配置、国内直连快、聚合多家 API;- 余额不退风险、偷偷降级、日志全留、单点故障。建议:日常测试 → 中转站;长期使用 → 自建反代(Oracle Free + Caddy,零成本);生产环境 → 自建反代 + IP 池 + 多源 fallback。

十七、掏心窝建议

  • 自建反代首选 Caddy,3 行配置,自动 HTTPS,比 nginx 简单 10 倍。
  • IP 被封别慌,先 curl https://api.openai.com/cdn-cgi/trace 看 IP 状态,再决定换 IP 还是套 CDN。
  • Cloudflare Workers 是反代终极方案:零成本 + IP 干净 + 全球 CDN,缺点是单次 10s 上限,长流式不行。
  • 中转站别充超过 50 元,跑路风险时刻存在,用完再充。
  • 反代公开 URL 一定要加鉴权,否则被白嫖 + 被风控双杀。
  • 免费层有配额,别拿来跑批量任务;多源切换凑齐 7 个免费源,日常用够了;OpenRouter $10 兜底;重度用老实充钱。

English Version

Translated from a linux.do community guide (Free Token Playbook, Part 2: Reverse Proxies & IPs). Part 1 covered free API channels; this part covers getting blocked: banned proxy IPs, OpenAI rejecting Chinese IPs, and relay stations disappearing.

1. Why you need a reverse proxy

Overseas APIs (OpenAI / Claude / Gemini): reject direct connections from Chinese IPs (“Country not supported”), check exit IP when you apply for a Key (Chinese IP = instant ban), and reject calls from Chinese VPSes too. Two solutions: A. Use a relay station (chatanywhere, SiliconFlow, etc.) — their servers are overseas and forward for you; B. Build your own reverse proxy on an overseas VPS.

2. Why IPs get banned

  • Chinese exit IP → Key application rejected
  • VPS IP ranges flagged by OpenAI (many cheap VPS ranges are blacklisted)
  • Multiple accounts applied from one IP → linked ban
  • Relay station IP got flagged → all users down together

Check if an IP is clean: curl https://api.openai.com/cdn-cgi/trace — if loc is US it’s fine, CN is not. Or open https://ipinfo.io and check country / ASN / VPN flag. Risky ranges: some BandwagonHost DC9/CN2 GIA, Alibaba Cloud Intl / Tencent Cloud Intl, some Vultr segments. Clean options: Oracle Cloud Free Tier (US Phoenix / Ashburn), AWS LightSail US ($3.5/mo), Cloudflare Workers (Cloudflare’s own IPs, cleanest), Hetzner / Contabo EU.

3. Option 1: Cloudflare Workers (zero cost, most recommended)

Proxy the target API through Cloudflare edge nodes — the IP is Cloudflare’s, clean worldwide. Free quota: 100K requests/day. Upside: zero cost, clean IP, global CDN. Downside: 10s limit per request, long streams get cut.

Steps: register a free Cloudflare account → Dashboard → Workers & Pages → Create Worker → paste:

export default {
  async fetch(req) {
    const url = new URL(req.url);
    const target = "https://api.openai.com" + url.pathname + url.search;
    const newReq = new Request(target, req);
    newReq.headers.set("Host", "api.openai.com");
    return fetch(newReq);
  }
}

You get https://your-subdomain.workers.dev — use it as base_url. Same config for Cline / Cursor / LobeChat. Pro tip: bind a custom domain (Workers → Triggers → Custom Domains) — workers.dev is sometimes blocked in China, custom domains aren’t.

4. Option 2: Overseas VPS + Nginx (most stable, for heavy use)

Needs an overseas VPS (Oracle Free / LightSail / Contabo). Stable, long connections, unlimited requests; costs time to configure.

apt install nginx -y
# /etc/nginx/conf.d/api-proxy.conf
server {
  listen 443 ssl;
  server_name api.your-domain.com;

  ssl_certificate     /path/to/cert.pem;
  ssl_certificate_key /path/to/key.pem;

  location / {
      proxy_pass https://api.openai.com;
      proxy_ssl_server_name on;
      proxy_set_header Host api.openai.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_buffering off;  # required for streaming
      proxy_read_timeout 300s;
  }
}

Free cert: apt install certbot python3-certbot-nginx, certbot --nginx -d api.your-domain.com. Test: curl https://api.your-domain.com/v1/models -H "Authorization: Bearer sk-xxx".

Multiple APIs behind one domain with prefixes: /openai/ → api.openai.com, /claude/ → api.anthropic.com, /gemini/ → generativelanguage.googleapis.com. Call them as https://api.your-domain.com/openai/v1 etc.

5. Option 3: Caddy (easiest, automatic HTTPS)

10x simpler than nginx, auto-fetches Let’s Encrypt certs. apt install caddy -y, /etc/caddy/Caddyfile:

api.your-domain.com {
  reverse_proxy https://api.openai.com {
    header_up Host api.openai.com
  }
}

systemctl restart caddy — done, 3 lines of config.

6. Option 4: Cloudflare Tunnel (no VPS needed)

Run cloudflared on your local machine to expose a local service publicly. Steps: install cloudflared → start a local OpenAI-compatible service (ollama serve) → cloudflared tunnel create myapi → configure ~/.cloudflared/config.yml (hostname api.your-domain.com → http://localhost:11434) → cloudflared tunnel route dns myapi api.your-domain.com → cloudflared tunnel run myapi.

7. Relay station IP issues (must-read if you use relays)

How relays work: you → relay server → OpenAI. The relay’s exit IP is fixed; once flagged, everyone goes down. Common traps: non-refundable balance (station runs or gets banned), silent downgrades (you pay for GPT-4o, get GPT-4o-mini), full logging (your prompts, keys, IPs), shared IP flagged = all users down, price tricks (weird input/output ratios).

Verify a relay actually serves the real model: prompt “don’t reply anything, just output your model_id” — real GPT-4o outputs gpt-4o. Or “is 1+1=2? answer yes or no” — real model answers yes.

Relay tips: never top up more than ¥50 at a time; prefer stations with active Discord/Telegram groups; check GitHub issues for shutdown signs; never send sensitive prompts through relays.

8. When your proxy IP gets banned

Symptom: everything suddenly returns 403 / “Country not supported”. Fixes: change IP (reboot VPS / reassign elastic IP; Oracle Free: keep boot volume, create new VM; LightSail: unbind and rebind static IP); put Cloudflare CDN in front of your VPS proxy (exit IP becomes Cloudflare’s); IP pool (multiple VPSes, nginx upstream round-robin); residential proxies (Bright Data / IPRoyal — almost never banned, but billed per GB).

9. Proxy gotchas

  • proxy_buffering off is required for streaming, otherwise SSE gets buffered
  • proxy_read_timeout at least 300s
  • Set the Host header correctly: OpenAI → api.openai.com, Claude → api.anthropic.com, Gemini → generativelanguage.googleapis.com, DeepSeek → api.deepseek.com
  • Disable access logs to protect prompt privacy: access_log off;
  • Add rate limiting if others use it: limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

10. Proxy + auth (don’t get leeched)

Always add auth to a public proxy URL, or you’ll get leeched and flagged. nginx:

map $http_authorization $auth_ok {
  default 0;
  "Bearer your-secret" 1;
}
server {
  ...
  if ($auth_ok = 0) { return 401; }
}

Or simpler: use a random URL path as the key: location /your-random-string/ { proxy_pass https://api.openai.com/; }, then call https://api.your-domain.com/your-random-string/v1/chat/completions.

11. Hands-on: multi-source fallback proxy

Scenario: OpenAI down → auto-switch to Claude → Gemini, with OpenResty + Lua. Try each upstream in order with ngx.location.capture; return the first 200 response, else 500.

12. IP hiding levels (weak → strong)

L0 direct → L1 HTTP proxy → L2 HTTPS proxy → L3 SOCKS5 → L4 VPN → L5 VPN + browser fingerprint spoofing → L6 residential proxy + fingerprint browser → L7 multi-hop. Minimum for API calls: L3 (SOCKS5 with overseas exit). After being flagged: L5+. Extreme: L7.

13. OpenAI registration IP blacklist cheat sheet

Likely rejected: Alibaba Cloud Intl (47.x / 39.x), Tencent Cloud Intl, Huawei Cloud Intl, some Vultr (108.x / 45.x) and DigitalOcean segments, some BandwagonHost DC9 CN2 GIA. Clean: Cloudflare Workers, Oracle Free Tier, AWS LightSail, Hetzner (EU), Azure US.

14. Common proxy errors cheat sheet

  • 403 Country not supported → IP rejected, change IP
  • 401 Unauthorized → wrong key or headers
  • 429 Too Many Requests → rate limited, sleep or switch accounts
  • 502 Bad Gateway → upstream is down
  • SSL_ERROR → cert or SNI misconfigured
  • “stream disconnected” → proxy_buffering not off
  • “Host header mismatch” → proxy_set_header Host not set
  • Slow calls → add proxy_http_version 1.1; + proxy_set_header Connection "";

15. Complete copy-paste nginx config

server {
  listen 443 ssl http2;
  server_name api.yours.com;

  ssl_certificate     /etc/letsencrypt/live/api.yours.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/api.yours.com/privkey.pem;

  access_log off;  # privacy
  error_log /var/log/nginx/api_error.log;

  proxy_read_timeout 600s;
  proxy_send_timeout 600s;

  limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;
  limit_req zone=api burst=10 nodelay;

  location / {
      proxy_pass https://api.openai.com;
      proxy_ssl_server_name on;
      proxy_set_header Host api.openai.com;
      proxy_set_header X-Real-IP "";
      proxy_set_header X-Forwarded-For "";
      proxy_http_version 1.1;
      proxy_set_header Connection "";
      proxy_buffering off;
      proxy_cache off;
      chunked_transfer_encoding on;
  }
}
server {
  listen 80;
  server_name api.yours.com;
  return 301 https://$server_name$request_uri;
}

Deploy: certbot --nginx -d api.yours.com, nginx -t && systemctl reload nginx.

16. Self-hosted proxy vs relay station

Self-hosted: full control, no log risk, unlimited (VPS bandwidth), unified entry for multiple APIs — but needs a VPS ($3.5+/mo, Oracle Free is free), nginx/caddy config, maintenance. Relay: zero config, direct fast connection in China, aggregates APIs — but non-refundable balance risk, silent downgrades, full logging, single point of failure. Recommendation: daily testing → relay stations; long-term → self-hosted (Oracle Free + Caddy, zero cost); production → self-hosted + IP pool + multi-source fallback.

17. Honest advice

  • Self-hosted proxy? Pick Caddy: 3 lines of config, auto HTTPS, 10x simpler than nginx.
  • IP banned? First run curl https://api.openai.com/cdn-cgi/trace to check IP status, then decide: change IP or put CDN in front.
  • Cloudflare Workers is the ultimate proxy: zero cost + clean IP + global CDN; downside is the 10s per-request limit.
  • Never top up a relay station more than ¥50 — shutdown risk is always there.
  • Always add auth to a public proxy URL, or you’ll be leeched and flagged at the same time.
  • Free tiers have quotas — not for batch jobs; rotate 7 free sources; $10 OpenRouter as fallback; for heavy use, just pay.

来源 / Source



评论(0)

查看评论列表

暂无评论


发表评论

表情 颜文字

插入代码