1. 程式人生 > >返回值過長時被nginx截斷的解決辦法

返回值過長時被nginx截斷的解決辦法

pen 過大 ons ext color buffer sed size fig

今天在寫接口時碰到了這個問題,返回json格式的數據,但是被截斷了
經過排查,才發現是數據過大超出緩沖區最大容量,而將數據寫入臨時文件時又沒有權限,所以再返回時,超出緩沖區的數據將丟失
解決方法:給fastcgi_temp 目錄賦讀寫權限
?
在nginx配置中的解釋

 1 Syntax:    fastcgi_buffers number size;
 2 Default: fastcgi_buffers 8 4k|8k;
 3 Context: http, server, location
 4 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. 5 6 Syntax: fastcgi_buffers number size; 7 Default: fastcgi_buffers 8 4k|8k; 8 Context: http, server, location 9 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. 10 11 Syntax: fastcgi_temp_path path [level1 [level2 [level3]]]; 12 Default: fastcgi_temp_path fastcgi_temp; 13 Context: http, server, location
14 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 15 fastcgi_temp_path /spool/nginx/fastcgi_temp 1 2; 16 a temporary file might look like this: 17 /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 目錄的寫權限,於是剩下的數據就丟失掉了。

返回值過長時被nginx截斷的解決辦法