返回值过长时被nginx截断的解决办法

今天在写接口时碰到了这个问题,返回json格式的数据,但是被截断了
经过排查,才发现是数据过大超出缓冲区最大容量,而将数据写入临时文件时又没有权限,所以再返回时,超出缓冲区的数据将丢失
解决方法:给fastcgi_temp 目录赋读写权限

在nginx配置中的解释

Syntax:    fastcgi_buffers number size;
Default: fastcgi_buffers 8 4k|8k;
Context: http, server, location
Sets the number and size of the buffers used for reading a response from the FastCGI server, for a single connection. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

Syntax:    fastcgi_buffers number size;
Default: fastcgi_buffers 8 4k|8k;
Context: http, server, location
Sets the number and size of the buffers used for reading a response from the FastCGI server, for a single connection. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

Syntax:    fastcgi_temp_path path [level1 [level2 [level3]]];
Default: fastcgi_temp_path fastcgi_temp;
Context: http, server, location
Defines a directory for storing temporary files with data received from FastCGI servers. Up to three-level subdirectory hierarchy can be used underneath the specified directory. For example, in the following configuration
fastcgi_temp_path /spool/nginx/fastcgi_temp 1 2;
a temporary file might look like this:
/spool/nginx/fastcgi_temp/7/45/00000123457

Nginx 的 buffer 机制,对于来自 FastCGI Server 的 Response,Nginx 将其缓冲到内存中,然后依次发送到客户端浏览器。缓冲区的大小由 fastcgi_buffers 和 fastcgi_buffer_size 两个值控制。
比如如下配置:
fastcgi_buffers 8 4K; 
fastcgi_buffer_size 4K;
fastcgi_buffers 控制 nginx 最多创建 8 个大小为 4K 的缓冲区,而 fastcgi_buffer_size 则是处理 Response 时第一个缓冲区的大小,不包含在前者中。所以总计能创建的最大内存缓冲区大小是 84K+4K = 36k。而这些缓冲区是根据实际的 Response 大小动态生成的,并不是一次性创建的。比如一个 8K 的页面,Nginx 会创建 24K 共 2 个 buffers。
当 Response 小于等于 36k 时,所有数据当然全部在内存中处理。如果 Response 大于 36k 呢?fastcgi_temp 的作用就在于此。多出来的数据会被临时写入到文件中,放在这个目录下面。
内存中缓冲了 36Kb,剩下的会写入的文件中。而实际的情况是,运行 Nginx Process 的用户并没有 fastcgi_temp 目录的写权限,于是剩下的数据就丢失掉了。

猜你喜欢

转载自blog.csdn.net/j6915819/article/details/80603846