`
gaozhonghui
  • 浏览: 237288 次
  • 性别: Icon_minigender_1
  • 来自: 内蒙古自治区
社区版块
存档分类
最新评论

nginx 利用 X-Accel-Redirect response header 控制文件下载

阅读更多
    自己开发的项目有下载的功能,刚开始的时候由于用户少,利用后台程序判断是否有下载权限,然后用流的方式输出到客户端。但是,随着用户的增加这种方式给服务器带来了压力。随后,想把下载的任务交给web 服务器来控制,但是这样又遇到了问题,我们怎样来控制它的下载权限呢?在网上找到了关于 nginx 利用  X-Accel-Redirect  header 来控制文件下载权限。自己也做了实验。

操作步骤:

1. 安装 nginx 服务器
   下载 nginx-1.0.10.tar.gz
  
    tar xvfz nginx-1.0.10.tar.gz
    cd  nginx-1.0.10
     ./configure --with-http_stub_status_module --prefix=/opt/nginx-1.0.10
     make
     make install
   

2. nginx 中下载控制相关配置
   根据下载的URI 配置 location 把可以下载 URI 设置成 "internal" 这样浏览器是不能直接访问的,我们只信任后台返回的 "X-Accel-Redirect",这样也就避免了客户端造 "X-Accel-Redirect" 下载文件情况,具体配置如下:
#### down zip faq files  #########
location /save/zip/ {
  internal; //拒绝浏览器直接访问
  limit_rate 200k;// 限制下载速度 和 limit_zone one $binary_remote_addr 配合使用
  alias /home/mindy/data4g12e/g12e_rsc/save/zip/; 
  error_page 404 =200 @backend; // 回调后台代理
}

location @backend {
  rewrite ^/save/zip/(.*)$  /download/getDownFile.jsp?path=/save/zip/$1 break; // 配置rewrite 跳到后台程序
 proxy_pass http://tomcatServer;
 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;
}

3. 后台程序控制 X-Accel-Redirect
在 getDownFile.jsp  中 代码
  String isPay = 1 // 判断用户是否可以下载 设置 response Header	
  if(isPay == 1){
	   response.setHeader("Content-Disposition","attachment;");
	   response.setHeader("Content-Type","application/octet-stream");
	   response.setHeader("X-Accel-Redirect",filePath);
   }

4. 配置完毕
e.g:
用户下载 http://down.xxx.com/save/zip/xxxxx.zip 文件
它会首先访问 http://down.xxx.com web服务器 符合"/save/zip/" location
会跳到后台服务器的 getDownFile.jsp 中,然看程序判断其是否可以下载 
若可以下载设置 response.setHeader("X-Accel-Redirect",filePath);
若不可以下载就不用设置 X-Accel-Redirect
分享到:
评论
1 楼 Aceslup 2016-08-15  
有一个地方不太明白,就是到这一步:若可以下载设置 response.setHeader("X-Accel-Redirect",filePath);这个返回给客户端的,还是给nginx的?

相关推荐

Global site tag (gtag.js) - Google Analytics