在Nginx中使用X-Sendfile头提升PHP文件下载的性能(针对大文件下载

2019-10-17 20:50:52丽君

使用 X-SendFile 的缺点是你失去了对文件传输机制的控制。例如如果你希望在完成文件下载后执行某些操作,比如只允许用户下载文件一次,这个 X-Sendfile 是没法做到的,因为后台的 php 脚本并不知道下载是否成功。

三、怎样使用?

Apache 请参考mod_xsendfile模块。下面我介绍 Nginx 的用法。

Nginx 默认支持该特性,不需要加载额外的模块。只是实现有些不同,需要发送的 HTTP 头为 X-Accel-Redirect。另外,需要在配置文件中做以下设定

location /protected/ {
 internal;
 root  /some/path;
}

表示这个路径只能在 Nginx 内部访问,不能用浏览器直接访问防止未授权的下载。


于是 PHP 发送 X-Accel-Redirect 给 Nginx:

]<?php
  $filePath = '/protected/iso.img';
  header('Content-type: application/octet-stream');
  header('Content-Disposition: attachment; filename="' . basename($file) . '"');
  //让Xsendfile发送文件
  header('X-Accel-Redirect: '.$filePath);
?>

这样用户就会下载到 /some/path/protected/iso.img 这个路径下的文件。
如果你想发送的是 /some/path/iso.img 文件,那么 Nginx 配置应该是

location /protected/ {
 internal;
 alias  /some/path/; # 注意最後的斜杠
}