Nginx

nginx、x-accel-redirect 和 mime 類型

  • October 28, 2019

在我的 nginx 0.8.34 設置中,我使用 X-Accel-Redirect 功能來控制應用程式碼中的文件下載,而不是讓應用程序自己處理下載。

在經歷了很多痛苦之後,這現在基本上可以工作了,除了 nginx 總是返回具有text/html內容類型的文件。

預設內容類型是應用程序/八位字節流,在http塊中指定。

除其他外,伺服器塊包含儲存文件的目錄的定義:

location /files {
 default_type  application/octet-stream;
 alias /srv/www/uploads;
 internal;  
}

所以我甚至在這裡指定了內容類型,但沒有任何改變。

我不想通過應用程序設置 Content-Type 因為那樣我會減慢我的速度(我首先必須確定它)。所以理想情況下,nginx 會根據文件副檔名返回正確的 mimetype(我確實在http塊中包含 mime.types)。

如果你想讓 nginx 猜測正確的 mime 類型,你只需要確保後端伺服器沒有返回內容類型。

With django:
   response = HttpResponse()
   response['Content-Type'] = ''
   response['X-Accel-Redirect'] ='/my/file.jpg'
   return response

我個人只是在應用程序中設置了 application/octet-stream,但您可以使用fastcgi_ignore_headers來防止 Nginx 使用後端提供的標頭。

fastcgi_ignore_headers Content-Type;

引用自:https://serverfault.com/questions/195060