【问题标题】:How to use Nginx X-Accel with Symfony?如何在 Symfony 中使用 Nginx X-Accel?
【发布时间】:2017-06-02 07:27:32
【问题描述】:

我想在 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 提供),我在 1ko/s 上添加了 X-Accel-Limit-Rate,但立即下载了 2Mo 文件,那么我确定,它不能正常工作。

我在互联网上找到了这部分代码,因为 Symfony 文档并没有真正解释如何使用它... (http://symfony.com/doc/current/components/http_foundation.html#serving-files)

为什么我需要返回带有文件的 BinaryResponse,比如没有 Nginx X-Sendfile,并在 resuqest 中添加 X-Sendfile、X-Accel 属性?我只是返回响应,没有请求,它是如何工作的?

【问题讨论】:

    标签: symfony nginx x-sendfile x-accel-redirect


    【解决方案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/;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-23
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多