Nginx 利用 X-Accel-Redirect response.setHeader 控制文件下載

nginx.confhtml

location / {
            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;
            proxy_pass http://backend;            
        }

location /file/ {
            internal;
            alias /usr/local/;
        }

設置成 "internal" 屬性是用來禁止瀏覽器直接訪問的,只信任後臺返回的 "X-Accel-Redirect"。nginx

getDownFile.jspredis

<%
    String filename = request.getParameter("filename");
    response.setHeader("Content-Disposition", "attachment;filename="+filename);
    response.setHeader("Content-Type", "application/octet-stream");
    response.setHeader("X-Accel-Redirect", "/file/"+filename);
%>


 http://10.10.3.205/test/getDownFile.jsp?filename=5.zip瀏覽器

請求到nginx後會發給Tomcat,先判斷是否能夠下載,若能夠下載設置X-Accel-Redirect回給nginx,nginx從新定位到物理文件進行下載。app

 

下面是JFinal的用法jsp

htmlspa

<a href="<%=path%>/redis_test/testResponse?id=1&filename=5.zip">下載</a>

後臺code

String filename = getPara("filename");
        String id = getPara("id");
        if(id.equals("1"))
        {
            getResponse().setHeader("Content-Type", "application/octet-stream");
            getResponse().setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("中文名.zip", "UTF-8"));
            getResponse().setHeader("X-Accel-Redirect", "/file/"+filename);
            
        } 
        renderNull();
相關文章
相關標籤/搜索