要让Nginx支持PHP-FPM处理OpenAI API的流式输出(如SSE或流式响应),需调整配置确保数据实时传输,避免缓冲阻塞。关键设置如下:
禁用Nginx缓冲:在PHP处理的location块中,关闭响应缓冲和压缩,确保数据即时发送:
location ~ \.php$ { fastcgi_pass unix:/run/php-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # 禁用缓冲 fastcgi_buffering off; proxy_buffering off; gzip off; }
PHP端配置:确保PHP脚本不缓冲输出,设置正确的响应头:
header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); header('X-Accel-Buffering: no'); // 关键:告知Nginx不缓冲 // 禁用PHP输出缓冲 ob_implicit_flush(true); ob_end_flush();
处理连接超时:若流持续时间长,需延长超时设置:
fastcgi_read_timeout 300s; # 调整为合适时长 proxy_read_timeout 300s;
这些设置确保Nginx和PHP-FPM不缓存流式数据,实现OpenAI API响应的实时输出。
网友回复