1、访问来源验证配置nginx
#文件访问来源校验 如路径:https://ys.test.com/test/api/uploads/test.png
#不是该允许域名的将返回403页面
location /test/api/uploads/ {valid_referers ys.test.com ys.test2.com;if ($invalid_referer) {return 403;}
}
2、拦截访问文件url交由后端内部判断是否有访问权限
nginx配置
#拦截文件访问url地址 如:https://ys.test.com/test/api/uploads/test.png
location /test/api/uploads/ {#开启只允许内部访问internal;error_page 404 =200 @backend;
}#内部php校验地址
location @backend {#进行访问地址重定向 # https://ys.test.com/test/api/uploads/test.png # -> # https://ys.test.com/test/api/down_auth/down/test.pngrewrite ^/test/api/uploads/(.*)$ /test/api/down_auth/down/$1 break;proxy_pass https://ys.yuhoutech.com;proxy_redirect off;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
php后端
<?php if (!defined('BASEPATH'))exit('No direct script access allowed');/*** 文件浏览权限判断*/
class Down_auth extends MY_Controller
{public function __construct(){parent::__construct();}/*** @Notes: 校验权限* @Function down*/public function down(){// 验证用户是否登陆 没登陆则返回获取文件失败$user_info = $this->session->userdata("user_info");if (empty($user_info)) {exit('get file failed!');}$base_dir = '/test/api/uploads/';// 图片真实存放路径$imagePath = $_SERVER['DOCUMENT_ROOT'] . $base_dir;// 获取url中的图片名 如 http://localhost/test/api/uploads/test.jpg 获取值为test.jpg$explode = explode("/", parse_url($_SERVER['REQUEST_URI'])['path']);$image = $explode[count($explode) - 1];// 拼接图片真实全路径 如 /var/www/test/api/uploads/test.jpg$fullPath = $imagePath . $image;//判断文件是否存在if (!file_exists($fullPath)) {exit('file 404 ');}// 获取图片mime信息 设置Content-type头$mime = getimagesize($fullPath)['mime'];header("Content-Type: $mime");// 设置sendfile头部,让nginx跳转到download下查找对应图片 相当于交给nginx进行后续处理header("X-Accel-Redirect: $base_dir/$image");}}
参考地址:
nginx静态文件权限控制-防盗链-CSDN博客
基于Nginx+PHP实现的带权限验证的静态文件服务器
springMvc+nginx文件鉴权(校验权限)服务器