您的位置:首页 > 运维架构 > Nginx

Nginx、Springmvc实现下载文件访问控制

2017-01-08 00:38 323 查看

Nginx利用X-sendfile结合Springmvc实现文件下载的访问控制(权限、积分、次数等)

1. 访问控制流程

请求下载地址:http://localhost/xxx-xxx/app/xxxx/4eecd20d9bdd45e9a6283105eb54fa0d

4eecd20d9bdd45e9a6283105eb54f : 请求文件的标识号,也可以放在header中。

xxx-xxx/app/xxxx : 为Springmvc请求地址

前端使用nginx进行监听,获取当前请求地址转发至web服务器。

应用服务器进行业务逻辑处理

设置setHeader -> X-Accel-Redirect

Nginx获取“X-Accel-Redirect”后以sendfile方式从NFS读取文件并进行下载

2. Spring Mvc代码

@RequestMapping(value = "/offline/{id}",method = RequestMethod.GET)
public void doDownloadOffline(@PathVariable("id") String offlineId,       HttpServletResponse response) throws IOException {

File zipFile = appCommonServiceImpl.selectOfflinePackageById(offlineId);
if (zipFile == null || !zipFile.exists()) {
response.sendError(404);
}
response.setHeader("Content-Type", "application/octet-stream");
//设置转发属性
// /appoffline/为Nginx location 名
response.setHeader("X-Accel-Redirect", "/appoffline/" + zipFile.getName());
response.setHeader("X-Accel-Charset", "utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
}


3. nginx.conf

location /app-all {
#root   html;
#index  index.html index.htm;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:8080/app-all; 
}

#设置文件存放path
location /appoffline/ {
#设置非浏览器访问
internal;
charset utf-8;
alias /app/offline/;
}


Nginx 403 forbidden 问题

权限问题(主要为权限问题):

在nginx.conf 里加入 user root 或者所属的能读取文件权限的用户;

目录不存在

如有疑问请加公众号(K171),如果觉得对您有帮助请 github start

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: