共计 3339 个字符,预计需要花费 9 分钟才能阅读完成。
背景痛点
国内开发者直接调用 ChatGPT API 时,经常会遇到以下问题:

- 网络延迟高,响应速度慢
- 访问不稳定,经常出现连接超时
- API 调用次数受限
- 直接访问可能违反某些网络政策
这些问题严重影响了开发效率和用户体验。为了解决这些问题,搭建一个国内镜像站成为了很多开发者的选择。
技术选型
在搭建镜像站时,主要有两种主流方案:
- Nginx 反向代理
- 优点:性能好,配置灵活,支持负载均衡
-
缺点:需要自行维护服务器
-
Cloudflare Workers
- 优点:无需维护基础设施,全球 CDN 加速
- 缺点:有免费额度限制,灵活性较差
对于需要高性能和自定义需求的场景,我们推荐使用 Nginx 反向代理方案。
核心实现
1. 使用 Docker 部署 Nginx
首先我们需要准备一个 Docker 环境,这里以 Ubuntu 系统为例:
-
安装 Docker
sudo apt-get update sudo apt-get install docker.io -
创建 Nginx 配置文件
# /etc/nginx/conf.d/chatgpt.conf server { listen 80; server_name your-domain.com; location / { proxy_pass https://api.openai.com; proxy_set_header Host api.openai.com; proxy_set_header X-Real-IP $remote_addr; } } -
启动 Nginx 容器
docker run -d --name nginx-chatgpt \ -p 80:80 -p 443:443 \ -v /etc/nginx/conf.d:/etc/nginx/conf.d \ nginx
2. Python 中间件实现
为了增强功能,我们可以添加一个 Python 中间件来处理 API 密钥轮换和限流:
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import httpx
app = FastAPI()
API_KEYS = ["sk-your-key1", "sk-your-key2"] # 多个 API 密钥
current_key_index = 0
@app.api_route("/{path:path}", methods=["GET", "POST"])
async def proxy(request: Request, path: str):
global current_key_index
# 限流检查
if should_rate_limit(request):
return JSONResponse({"error": "rate limit exceeded"}, status_code=429)
# 构建请求
headers = dict(request.headers)
headers["Authorization"] = f"Bearer {API_KEYS[current_key_index]}"
# 轮换 API 密钥
current_key_index = (current_key_index + 1) % len(API_KEYS)
async with httpx.AsyncClient() as client:
resp = await client.request(
request.method,
f"https://api.openai.com/{path}",
headers=headers,
data=await request.body())
return JSONResponse(resp.json(), status_code=resp.status_code)
3. 添加 HTTPS 支持
为了安全考虑,我们需要为域名添加 HTTPS 支持:
-
申请 SSL 证书(可以使用 Let’s Encrypt)
sudo apt-get install certbot python3-certbot-nginx sudo certbot --nginx -d your-domain.com -
更新 Nginx 配置
server { listen 443 ssl; server_name your-domain.com; ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; location / { proxy_pass https://api.openai.com; proxy_set_header Host api.openai.com; proxy_set_header X-Real-IP $remote_addr; } }
性能优化
连接池配置
在 Nginx 配置中添加连接池设置可以显著提高性能:
http {
upstream openai_backend {
server api.openai.com:443;
keepalive 32; # 连接池大小
}
server {
location / {
proxy_pass https://openai_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
}
超时设置
合理设置超时可以避免长时间等待:
location / {
proxy_pass https://api.openai.com;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
合规运营
用户认证
建议添加基础认证来限制访问:
-
生成密码文件
sudo htpasswd -c /etc/nginx/.htpasswd username -
更新 Nginx 配置
location / { auth_basic "Restricted Access"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass https://api.openai.com; }
访问日志
记录详细的访问日志有助于监控和分析:
log_format chatgpt '$remote_addr - $remote_user [$time_local]'
'"$request" $status $body_bytes_sent ''"$http_referer""$http_user_agent" ''$request_time $upstream_response_time';
access_log /var/log/nginx/chatgpt-access.log chatgpt;
避坑指南
- 错误:证书过期
-
解决方案:设置自动续期
echo "0 0 1 * * /usr/bin/certbot renew --quiet" | sudo tee -a /etc/crontab > /dev/null -
错误:API 密钥泄露
-
解决方案:定期轮换密钥,不在代码中硬编码
-
错误:流量突增导致服务不可用
- 解决方案:实施严格的限流策略
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from slowapi import Limiter from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter @app.get("/") @limiter.limit("5/minute") async def home(request: Request): return {"message": "Hello"}
总结与思考
通过本文,我们完整实现了一个具备基本功能的 ChatGPT 国内镜像站。但在实际生产环境中,还有更多需要考虑的因素:
- 如何实现更精细化的流量控制和计费?
- 在多地域部署时,如何保证服务的高可用性?
- 面对突发的流量增长,自动扩缩容策略应该如何设计?
这些问题留给读者进一步思考和探索。希望这篇文章能为你搭建自己的 AI 服务提供有价值的参考。
正文完
