使用nginx下载静态资源的控制

需求

1、静态资源放到指定文件夹下

2、nginx直接访问无法获取

3、后台走JAVA程序控制

4、用户获取仍然走nginx,不走JAVA后台

进行nginx配置

对X-Accel-Redirect理解:

X-Accel-Redirect response header makes an internal redirection to a locationblock determined by header's value returned from an upstream (backend).

https://zaiste.net/nginx_x_accel_header/

 server {
        listen       80;
        server_name  dl.mydomain.com;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        
        #这个location的使用主要是为了让用户使用ip地址直接访问,不需要再走Tomcat的端口号访问
        location / {
		
            proxy_pass  http://127.0.0.1:8080/;  #首先pass到应用服务器
            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;

            client_max_body_size       10m;
            client_body_buffer_size    128k;

            proxy_connect_timeout      90;
            proxy_send_timeout         90;
            proxy_read_timeout         90;

            proxy_buffer_size          4k;
            proxy_buffers              4 32k;
            proxy_busy_buffers_size    64k;
            proxy_temp_file_write_size 64k;
        }
		
        #这个地方是真正的静态文件的访问地址,后台java程序会控制原访问路径跳转到该路径下:http://域名/pic/文件名;此时nginx会使用alias路径代替pic
	location /pic/ { 
            charset utf-8;
            alias       /var/pic/; #文件的根目录(允许使用本地磁盘,NFS,NAS,NBD等)
            internal;#防止用户直接访问:http://域名/pic/文件名
        }

JAVA后台控制

/**
 * @author zongx
 * 下载文件实现类
 */
@RequestMapping("/v3/download")
public class V3DownloadController {

	protected static final String DEFAULT_FILE_ENCODING = "ISO-8859-1";

    @RequestMapping(value = "/pic")
	public void downloadPic(HttpServletRequest request, final HttpServletResponse response) throws IOException {
    	//读取要下载的文件的名称
		String name = request.getParameter("name");
		
		//读取要进行判断的request的条件
		String ok = request.getParameter("ok") == null ? "" :  request.getParameter("ok");
		
		//判断条件
		if( ok.equals("ok")) {			
			//获取文件的真实位置。可以通过配置文件设置前置路径,此处文件路径写死
			String filepath = "/var/pic/"+name;
			
			//判断文件是否存在
			File file = new File(filepath);
			if (file != null && file.exists()){
				
				//重定向到nginx的方法,主要是设置文件头
				xAccelRedirectFile(file, response);

			} else { 
				response.sendError(404);
			}
		} else {
			response.sendError(404);
		}
		
	}

	protected void xAccelRedirectFile(File file, HttpServletResponse response) 
		throws IOException {
		
		String encoding = response.getCharacterEncoding();
		
		//设置文件头的Content-Type,固定写法
		response.setHeader("Content-Type", "application/octet-stream");
		
        //这里获取到文件的相对路径。其中 /pic/的目的是用于nginx中进行拦截/pic/ 的URL。对应nginx里的location /pic/
		response.setHeader("X-Accel-Redirect", "/pic/"
				+ toPathEncoding(encoding, "1.jpg"));
		
		response.setHeader("X-Accel-Charset", "utf-8");
		
		//返回iso-8859-1对应的文件名称
		response.setHeader("Content-Disposition", "attachment; filename="
				+ toPathEncoding(encoding, file.getName()));
		
		//返回文件大小
		response.setContentLengthLong(file.length());
	}

    //如果存在中文文件名或中文路径需要对其进行编码成 iSO-8859-1
    //否则会导致 nginx无法找到文件及弹出的文件下载框也会乱码
	private String toPathEncoding(String origEncoding, String fileName) throws UnsupportedEncodingException{
		return new String(fileName.getBytes(origEncoding), DEFAULT_FILE_ENCODING);
	}

}

思想:

主要思想,就是先访问JAVA后台,确定要不要进行重定向回nginx。nginx负责静态文件的返回用户,只要接收到java后台的X-Accel-Redirect信号,就返回用户文件。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值