nginx控制静态资源访问权限 | 您所在的位置:网站首页 › 如何设置浏览器的代理访问限制呢 › nginx控制静态资源访问权限 |
问题背景
一些静态资源如图片、html等,如果文件地址暴露,不需要权限也能访问。鉴于这种情况,对静态文件的直接访问需要进行权限判定 解决方案使用 nginx 的 internal rewrite 等指令 location /DATA/PREVIEW { internal; alias /data/preview; error_page 404 =200 @auth_check; # 或 # error_page 404 =403 @auth_check; } location @auth_check { rewrite ^/DATA/PREVIEW/(.*)$ /demo/test?path=/DATA/PREVIEW/$1 break; proxy_pass http://localhost; 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; }internal 和 error_page 的作用 官方文档:http://nginx.org/en/docs/http/ngx_http_core_module.html internal,Nginx会拒绝处理来自客户端的直接请求,仅允许内部调用 权限校验伪代码: @RequestMapping("/test") @ResponseBody public void test(HttpServletRequest request, HttpServletResponse response) throws IOException { // 在这里做权限校验 if(noAuth) { response.sendError(403); retrun; } String path = request.getParameter("path"); path = URLEncoder.encode(path, "UTF-8"); String fileExt = path.substring(path.lastIndexOf('.') + 1).toUpperCase(); boolean download = true; switch (fileExt) { case "JPEG": case "JPG": response.setContentType(MediaType.IMAGE_JPEG_VALUE); download = false; break; case "GIF": response.setContentType(MediaType.IMAGE_GIF_VALUE); download = false; break; case "PNG": response.setContentType(MediaType.IMAGE_PNG_VALUE); download = false; break; default: break; } if (download) { response.setHeader("Content-Type", "application/octet-stream"); // 下载 response.setHeader("Content-Disposition", "attachment;"); } response.setHeader("X-Accel-Redirect", path); response.setHeader("Cache-Control", "no-store"); // HTTP 1.1 response.setHeader("Pragma", "no-cache"); // HTTP 1.0 response.setDateHeader("Expires", 0); response.setDateHeader("max-age", 0); } 分析path = URLEncoder.encode(path, “UTF-8”) 的作用 显而易见,这行代码是对path参数进行URLEncoder。X-Accel-Redirect放在response head中,很多情况下head是不支持中文的。如果path参数中带有中文,可能产生不符合预期的结果 测试.html不存在
题外话:对于中英文混合的文件名,例如test一二三.html,中文在前和英文在前的结果也是不一样的。如果是test一二三.html,那么结果是404,如果是一二三test.html,那么结果是403 X-Accel-Redirect 的作用 参考官方文档:https://www.nginx.com/resources/wiki/start/topics/examples/x-accel Cache-Control 的作用 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control Pragma 的作用 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Pragma auth_request除了上述方法,使用auth_request指令也能实现同样的效果 location /pub { auth_request /pub/auth; alias /data/pub; } location = /pub/auth { internal; proxy_pass http://localhost/demo/test?path=$request_uri; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Original-URI $request_uri; }需要注意的是,auth_request只接受4种返回码: 2xx、401、403和 500。如果出现404错误,最终的返回结果会是500。 |
CopyRight 2018-2019 实验室设备网 版权所有 |