PHP 利用nginx的X-sendfile控制下载,提高下载效率

https://blog.csdn.net/qq_34839657/article/details/52812885

https://www.jianshu.com/p/bf5c387830b7

 

为了控制静态文件下载,

一般方法需要PHP用file_get_contents读取文件,再传给客户端。

节省资源的方法是利用nginx的x-sendfile模块

原理是 nginx 上设置一个特殊资源目录,客户端无法直接读取,需要经过php许可后才能下载。

1、设置nginx

location /request/uri/ {
    internal;
    alias /real/path/;
}

目录 /request/uri/ 被设置为 internal, 所以客户端无法直接访问。

alias 对应的文件所在真实目录,一般这个目录不在公开目录下,也无法访问。

注意要设置生效。

nginx -s reload

2、访问php

// 验证是否有权限: 费这么大劲就是为了这个

// 获取要下载的文件名称: $p_file = '/request/uri/filename.ext';                     

// 告诉nginx放行:
header('Content-type: application/octet-stream');
// 这里的$fileName = basename($p_file) 也就是 filename.ext
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// nginx sendfile
header('X-Accel-Redirect: '.$p_file);

 

还有一些控制选项,需要提前 X-Accel-Redirect 发送

X-Accel-Limit-Rate: 1024
X-Accel-Buffering: yes|no
X-Accel-Charset: utf-8

文档:https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/

 

posted @ 2019-03-13 16:26  忘忧般若汤  阅读(682)  评论(0编辑  收藏  举报