2017-06-02 58 views
1

我想使用Nginx的X-Accel與Symfony,目前我有這個代碼。如何在Symfony中使用Nginx X-Accel?

$request->headers->set('X-Sendfile-Type', 'X-Accel-Redirect'); 
    $request->headers->set('X-Accel-Mapping', '/var/www/html/files/=/protected-files/'); 
    $request->headers->set('X-Accel-Limit-Rate', '1k'); 

    BinaryFileResponse::trustXSendfileTypeHeader(); 
    $response = new BinaryFileResponse($file->getAbsolutePath()); 
    $response->headers->set('Content-Disposition', 'attachment;filename="'.$filename.'"'); 
    $response->headers->set('Cache-Control', 'no-cache'); 

    return $response; 

而且Nginx的CONF:

location /protected-files { 
    internal; 
    alias /var/www/html/files; 
} 

測試代碼(如果知道該文件是真的Nginx的服務),我已經加入X-加速漲停價上1KO/s,但是2Mo文件被立即下載,然後我確定,它不能正常工作。

我已經找到互聯網上的這部分代碼,因爲Symfony的文檔,並沒有真正解釋如何使用它......(http://symfony.com/doc/current/components/http_foundation.html#serving-files

爲什麼我需要用文件返回BinaryResponse,就像沒有Nginx的X-Sendfile一樣,並在結果中添加X-Sendfile,X-Accel屬性?我只是返回響應,沒有請求,它如何工作?

回答

1

最後,我將X-Accel部分從$ request移動到$ response,然後設置X-Accel-Redirect標題。

如果我們想限制下載速度,我們可以使用$request->headers->set('X-Accel-Limit-Rate', 10000);,它工作的很好,數字以字節爲單位。

然後,我已經改變$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename.'"');$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);

最後的代碼是:

BinaryFileResponse::trustXSendfileTypeHeader(); 
$response = new BinaryFileResponse($file->getAbsolutePath()); 
$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT, 
    $filename 
); 
$response->headers->set('X-Accel-Redirect', '/protected-files/path/to/file'); 

return $response; 

而在Nginx的:

location /protected-files/ { 
    internal; 
    alias /var/www/html/files/; 
}