How to force file download in the browser, nginx s

2019-04-21 20:45发布

I currently have 2 image locations and they may the formats (jpg,jpeg,png,gif)

i.domain.com/simage.jpg thumbnail
i.domain.com/image.jpg high quality
i.domain.com/o/image.jpg full resolution

Does anyone know how I can force image files in /o/ to download rather than render in the web browser?

Here's my conf file: http://pastebin.com/dP8kZMzx

#setup subdomain i.domain.com
server {
    server_name i.domain.com;
    access_log /var/log/nginx/i..com.access.log;
    error_log /var/log/nginx/i.domain.com.error.log;

    root /var/www/domain.com/test1/images;
    index index.php index.html index.htm;

    #error_page 403 = /notfound.jpg;
    #error_page 500 = /notfound.jpg;

    location / {            
        #change this to a 404 img file .jpg
        try_files $uri $uri/ /notfound.jpg;

        rewrite  "/s([A-Za-z0-9.]+)?" /small/$1 break;
        rewrite  "/o/([A-Za-z0-9.]+)?" /orig/$1 break;
        rewrite  "/([A-Za-z0-9.]+)?" /medium/$1 break;
    }

}

3条回答
欢心
2楼-- · 2019-04-21 21:13

I have been trying to get this functionality into my own nginx server.

I have a folder on server that I would like to have open for anyone who knows the path.

To do that I added a /file/ location into my nginx config file.

server {
   listen 80;
   server_name example.com;

   location /file/ {
       alias /var/openStuff/file/;
       add_header Content-disposition "attachment";
   }
}

Any request to example.com/file/x will go to /var/openStuff/file and look for x and force the browser to download the file

This will also work if the path is /file/stuff/things.txt and will serve it from /var/openStuff/file/stuff/things.txt

查看更多
爷的心禁止访问
3楼-- · 2019-04-21 21:22

You just need to return HTTP header Content-disposition:

location ~* /orig/(.+\.jpg)$ {
    add_header Content-disposition "attachment; filename=$1";
}
查看更多
Evening l夕情丶
4楼-- · 2019-04-21 21:23

Below config works for me.

server {
    ...
    # Django media
    location /media  {
        alias /var/www/media;  
        types { application/octet-stream .pdf; }
        default_type application/octet-stream;
    }
    ...
}

But the pdf file needs to ends with lowercase pdf for download to work. I still don't know the syntax to add both .pdf and .PDF to above config file. Any suggestion? The answer is based on info from http://210mike.com/force-file-download-nginx-apache/

查看更多
登录 后发表回答