我们知道,使用nginx作为文件下载服务器,可以极大地降低对后端Java服务器的负载冲击,但是nginx本身并不提供授权控制,因此好的方案是由后端服务器实现权限控制,最好的方式是直接复用应用的认证体系,最大化的降低成本。因此,可借助http的"X-Accel-Redirect"头实现该特性。具体如下:
location /bookres/ {
#禁止浏览器直接访问
internal;
limit_rate 200k;
alias d:/test/bookres/;
#转由后台处理(tomcat等web容器)
error_page 404 =200 @backend;
}
location @backend {
rewrite ^/bookres/(.*)/(.*)/(.*)/(.*)$ /bookres/?isbn=$1&restype=$2&resid=$3&type=$4 break;
proxy_pass http://localhost:8081; #tomcat等web容器
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;
break;
}
java后台代码如下:
httpResponse.setHeader("Content-Disposition",
"attachment; filename=\""+filename+"\"");
httpResponse.setHeader("Content-Type",
"application/octet-stream");
httpResponse.setHeader("X-Accel-Redirect",
"/bookres/"+resource.get("res_url"));
//给nginx返回实际文件存在的地址
相比采用其他文件服务器方案如sftp/fastdfs/mongodb而言,该方案明显轻量非常多。但是它不提供存储高可用,如果需要高可用和弹性扩展的话,clusterfs可算是linux下最普世的方案之一。https://zhuanlan.zhihu.com/p/28627829、https://blog.csdn.net/weixin_30713953/article/details/97227167、https://www.cnblogs.com/Csir/p/6820355.html、http://www.mamicode.com/info-detail-2229237.html。
如果是块级存储的话,就没有fastdfs和ceph来的省事了,https://blog.csdn.net/qq_27384769/article/details/80603530,其他文件系统的对比可参考https://blog.csdn.net/zhanggqianglovec/article/details/104009602。
