在进行WEB开发时, 必然会遇到文件下载、视频播放等场景, 当操作的文件较小时, 我们可以在后端代码进行完鉴权后加载文件,通过数据流的方式返回,其实也不推荐,因为body 有默认大小限制,还要改大limit,速度也慢, 但是当文件较大时, 再使用接口中返回数据流的方式就显得极其不合适了. 此时, 就需要通过 nginx 读取文件资源向用户进行返回.
但是, 如果当用户进行文件请求时, 我们需要对用户进行身份认证(如视频VIP会员, 文档保密需求, 图片防盗用等等), 这时我们就需要对 nginx 进行配置, 限制任意用户进行访问目标文件, 将其设置仅限内部调用.
当用户发起文件请求:
第一步, 先将用户的请求导向web应用层, 并进行用户身份的认证
第二步, 认证通过, 在web应用层发起内部调用, 由nginx返回文件, 否则返回 403(直接访问文件返回404)
nginx.conf:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /code;
index index.php index.html index.htm;
}
location ~ \.php {
set $script $uri;
set $path_info "";
if ($uri ~ "^(.+.php)(/.+)") {
set $script $1;
set $path_info $2;
}
root /code;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /code$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $script;
fastcgi_param PATH_INFO $path_info;
include fastcgi_params;
}
#主要添加配置
# 这里使用internal做下载防护,只允许内部程序访问,这样外部直接访问这个地址就会提示404错误
location /private_files/ {
internal;
#文件存放路径
alias /code/private_files/;
}
}
}
auth.php:
<?php
//传入的文件路径
$file = '/code/private_files/1581410556698554.mp4’;
//TODO 鉴权判断
$authCheck = true;
if ($authCheck) {
header('Content-Type:application/octet-stream;');
header("Content-type: video/mp4");
header('Content-Disposition: attachment; filename=' . $file);
header('X-Accel-Redirect: /private_files/' . basename($file));
} else {
echo '无权限';
}