思路:
文件下载请求 到 后台;后台判断权限,不通过则不下载;通过则设置 X-Accel-Redirect;Nginx获取“X-Accel-Redirect”后以sendfile方式从NFS读取文件并进行下载
回到顶部
优点:
- 不会直接暴露文件地址 抓包工具不会抓到地址;
- 可以控制权限;
回到顶部
后台示例代码:
1 @RequestMapping(value = "/offline", method = RequestMethod.GET) 2 public void doDownloadOffline(HttpServletResponse response) throws IOException { 3 4 File zipFile = new File("/Users/lixiuming/Desktop/test.json"); 5 if (zipFile == null || !zipFile.exists()) { 6 response.sendError(404); 7 } 8 response.setHeader("Content-Type", "application/octet-stream"); 9 // 设置转发属性 10 // /appoffline/为Nginx location 名 11 response.setHeader("X-Accel-Redirect", "/appoffline/" + zipFile.getName()); 12 response.setHeader("X-Accel-Charset", "utf-8"); 13 response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName()); 14 }
传参示例:
View Code
说明:
- /appoffline/为Nginx location 名;
- 这里的 @RequestMapping(value = "/offline", method = RequestMethod.GET),/offline;当监听到 Nginx监听到 /download_file时,访问了后台(地址是/offline)
回到顶部
nginx.conf配置代码:
1 location / { 2 root html; 3 proxy_pass https://www.baidu.com; 4 index index.html index.htm; 5 } 6 7 location = /download_file { 8 proxy_pass http://127.0.0.1:8080/offline; 9 } 10 location /appoffline/ { 11 #设置非浏览器访问 12 internal; 13 charset utf-8; 14 alias /Users/lixiuming/Desktop/; 15 }
说明:当访问 http://localhost:8081/download_file?file_id=1 (不传参地址http://localhost:8081/download_file) 时,可以执行下载文件,F12 NETWORK 没有文件地址;