我們知道,使用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。