CloudFlare Worker反向代理Openai

主要解决被官网拦截和国内不能访问慢的问题

Copy
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request));
})

async function fetchAndApply(request) {

let response = null;
let method = request.method;

let url = new URL(request.url);
let url_hostname = url.hostname;
url.protocol = 'https:';
url.host = 'api.openai.com';

let request_headers = request.headers;
let new_request_headers = new Headers(request_headers);
new_request_headers.set('Host', url.host);
new_request_headers.set('Referer', url.protocol + '//' + url_hostname);

let original_response = await fetch(url.href, {
method: method,
headers: new_request_headers,
body: request.body
})

let original_response_clone = original_response.clone();
let original_text = null;
let response_headers = original_response.headers;
let new_response_headers = new Headers(response_headers);
let status = original_response.status;

new_response_headers.set('Cache-Control', 'no-store');
new_response_headers.set('access-control-allow-origin', '*');
new_response_headers.set('access-control-allow-credentials', true);
new_response_headers.delete('content-security-policy');
new_response_headers.delete('content-security-policy-report-only');
new_response_headers.delete('clear-site-data');

original_text = original_response_clone.body
response = new Response(original_text, {
status,
headers: new_response_headers
})

return response

}

** 虽然可以实现，但会导致账号被封建议使用自己的 vps 反向代理 **

Nginx 配置反向代理

打开 Nginx 配置文件（通常是 /etc/nginx/nginx.conf）。

在 http 块内添加以下代码：

Copy
server {
listen 80;
server_name yourdomain.com; # 替换为您自己的域名

location / {
return 301 https://$host$request_uri;
}
}

server {
listen 443 ssl;
server_name yourdomain.com; # 替换为您自己的域名

ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/certificate.key;

location / {
proxy_pass https://api.openai.com;
proxy_set_header Host api.openai.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Cache-Control' 'no-store';
}
}

两个 server，一个监听 80 端口，用于将所有 HTTP 请求重定向到 HTTPS；另一个监听 443 端口并启用 SSL，用于处理 HTTPS 请求。我们使用 location / 定义了一个代理服务器，当用户请求该目录时，Nginx 将会将其转发到 https://api.openai.com。

请注意替换 yourdomain.com 为您自己的域名，并将 /path/to/your/certificate.crt 和 /path/to/your/certificate.key 替换为您的 SSL 证书路径。