nginx配置下载服务器(具备权限验证)
大多数场景中,下载可以使用nginx直接代理,但缺少权限验证,下述方式下载通过后端校验,成功后转发请求nginx进行下载操作。
前端代码:
window.location.href = "http://192.168.80.128:8080/download_file?fileName=8042200341080001_01.zip";
直接打开访问指定的下载文件路径(我是用请求时必须携带token才能访问后端,否则进不了后端,就谈不上下载了),之后验证是否有该文件,有则进行下载操作。
后端代码:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void doDownloadOffline(String fileName, HttpServletResponse response) throws IOException {
log.info("进入下载20240817:{}", fileName);
if (fileName != null ) {
File zipFile = new File("/Data/data/" + fileName);
if (!zipFile.exists()) {
response.sendError(404);
}
response.setHeader("Content-Type", "application/octet-stream");
// 设置转发属性
response.setHeader("X-Accel-Redirect", "/downloadFile/" + zipFile.getName());
response.setHeader("X-Accel-Charset", "utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + zipFile.getName());
log.info(response.toString());
} else {
System.out.println("error");
}
}
其中“/Data/data/”是服务器上文件所在目录,当文件真实存在时,重定向到“/downloadFile/”+ 文件名进行下载。
nginx配置:
server {
listen 8080;
server_name 192.168.80.128;
location / {
root /home/java/blog/web/dist/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://192.168.80.128:8888/;
}
location = /download_file {
proxy_pass http://192.168.80.128:8888/download;
}
location /downloadFile/ {
#设置非浏览器访问
internal;
charset utf-8;
alias /Data/data/;
}
}
前端访问,nginx转发到 “http://192.168.80.128:8888/download” 到后端进行验证,验证通过后,转发到“/downloadFile/” 进行下载。
以上完毕
浙公网安备 33010602011771号