Mainly solve the problems of being intercepted by the official website and slow access in China#
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
}
Although it can be implemented, it may cause the account to be blocked. It is recommended to use your own VPS reverse proxy.
Nginx configuration reverse proxy#
- Open the Nginx configuration file (usually /etc/nginx/nginx.conf).
- Add the following code within the http block:
server {
listen 80;
server_name yourdomain.com; # Replace with your own domain name
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name yourdomain.com; # Replace with your own domain name
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';
}
}
There are two servers, one listening on port 80, which redirects all HTTP requests to HTTPS; the other listening on port 443 and enabling SSL, which handles HTTPS requests. We use location / to define a proxy server, so when users request this directory, Nginx will forward it to https://api.openai.com.
Please note that you should replace yourdomain.com with your own domain name, and replace /path/to/your/certificate.crt and /path/to/your/certificate.key with your SSL certificate paths.