通过配置 Nginx 反向代理,利用海外服务器中转请求,解决国内环境无法直接访问 OpenAI API 的问题。

Nginx 配置示例

在 Nginx 配置文件(如 nginx.confconf.d/openai.conf)中添加以下 server 块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
server {
listen 443 ssl;
server_name your.domain.com; # 替换为你的域名

# SSL 证书配置
ssl_certificate /path/to/your/cert.pem;
ssl_certificate_key /path/to/your/key.pem;

# SSL 优化配置 (可选)
ssl_session_cache shared:le_nginx_SSL:1m;
ssl_session_timeout 1440m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:!MD5;

location / {
# 反向代理到 OpenAI
proxy_pass https://api.openai.com/;

# 关键配置:启用 SNI,否则握手会失败
proxy_ssl_server_name on;

# 修改 Host 头
proxy_set_header Host api.openai.com;

# 关闭连接保持,避免长时间占用
proxy_set_header Connection '';
proxy_http_version 1.1;

# 优化传输
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;

# 传递客户端 IP (可选)
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

配置完成后,使用 nginx -t 检查配置,并重启 Nginx。
客户端调用时,将 https://api.openai.com 替换为 https://your.domain.com 即可。