美文网首页IT我爱编程
PHP 通过Nginx x-sendfile实现文件鉴权下载

PHP 通过Nginx x-sendfile实现文件鉴权下载

作者: forever_youyou | 来源:发表于2018-08-09 16:13 被阅读59次

通过php鉴权,文件下载由 nginx 实现;
比使用php readfile() 高效;

# nginx 配置
location /auth_download {
    internal; # 这个设置是必需的
    alias /data/upload; # 文件所在真实路径
}
<?php
if (!isset($_GET['file'])) {
    die('文件不存在');
}
$file = $_GET['file'];
$rename = isset($_GET['rename']) ? $_GET['rename'] : $file;
// 模拟校验下载权限
$canDownload = rand(1, 2) == 1;
if ($canDownload) {
    header('Content-Type:application/octet-stream;');
    header('Content-Disposition: attachment; filename=' . $rename);
    header('X-Accel-Redirect: /auth_download/' . ltrim($file, '/'));
} else {
    echo '无权限';
}

比如下载的文件为: /data/upload/1.zip,php 代码只要
header('X-Accel-Redirect: /auth_download/1.zip') 即可下载对应文件;

参考:
x-sendfile: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/
X-Accel-Redirect:https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/

相关文章

网友评论

    本文标题:PHP 通过Nginx x-sendfile实现文件鉴权下载

    本文链接:https://www.haomeiwen.com/subject/wulcbftx.html