当前位置: 首页> 文旅> 酒店 > Nginx+PHP+CI框架实现,访问静态文件带权限验证

Nginx+PHP+CI框架实现,访问静态文件带权限验证

时间:2025/7/9 6:05:15来源:https://blog.csdn.net/qq_36478642/article/details/140827242 浏览次数:0次

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文件鉴权(校验权限)服务器

 

关键字:Nginx+PHP+CI框架实现,访问静态文件带权限验证

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: