Problem with nginx handling the actual path of images
怪我咯
怪我咯 2017-05-16 17:21:57
0
1
515

In the project, the uploaded files are renamed by sha1. After a picture is uploaded, it is named c2e47454e951697811c0531949d4d318
The access path on the browser side is: /img/c2e47454e951697811c0531949d4d318. Note that there is no suffix name for the picture. !

After I deploy, I need to do caching through nginx. So, let me ask you guys, how should I deal with it:

怎么在nignx里配置映射到真实的 image_save_path/img/c2/e4/7454e951697811c0531949d4d318.[jpg|gif|png]

location ~/img/*$ {
    root image_real_path_here;
    # 此处不太理解该如何处理图片名称的前四个字符,变成路径形式,        
}

Please help me a lot! Thanks

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
仅有的幸福

First of all, since you have already sha1'd it, you don't need to store its suffix. When storing, change everything to the sha1 value

Then, if you directly access Nginx to get the image, you will not get the correct file name, and some other logic is not easy to handle, so just write a controller to handle it:

    @RequestMapping(value = "imgs/{sha1}/download", method = RequestMethod.GET)
    @ResponseBody
    public HttpEntity<byte[]> downloadAttachment(@PathVariable("sha1") String sha1)
            throws UnsupportedEncodingException {
        Attachment attachment = attachmentService.getBySha1(sha1);

        if (attachment == null) {
            throw new ResourceNotFoundException();
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String filename = new String(attachment.getName().getBytes("GB2312"), "ISO_8859_1");
        header.setContentDispositionFormData("attachment", filename);
        header.add("X-Accel-Redirect", String.format("/img/c2/e4/%s", sha1));
        header.add("X-Accel-Charset", "utf-8");

        return new HttpEntity<byte[]>(null, header);
    }

In this way, you can not only use Nginx’s cache, but also use your own code to do some logical operations, and you can also add the function of permission judgment

In addition, Nginx configuration does not need to be changed

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template