Configuration method for forced downloading of Nginx files

Scenario
1:
Adding header information Content-Disposition "attachment;" will force the browser to download:

code show as below:

#Indicates that the browser displays a file
inline Content-disposition: inline; filename=foobar.pdf
 
#Indicates that the file will be downloaded, such as Firefox
Content-disposition: attachment; filename=foobar.pdf
nginx configuration is as follows, in the corresponding server Add the following location:

code show as below:

location /download {
    add_header Content-Disposition "attachment;";
}


Scene two:

There is such a demand. For file links such as image files and PDFs, as long as the access is under a certain path, the image cannot be opened in the browser. Instead, the user is prompted to save it locally, and the file name uses the accessed file name.
This problem is mainly caused by IE. No matter what the mime type is, for example, if the mime type of the image is manually set to octet-stream, if the browser recognizes the file suffix, the image will still be opened in the browser.

solution:

Add in the http header of the response: Content-Disposition: attachment; filename=filename
nginx configuration is as follows:

code show as below:

  location ~ ^/somepath/(.*)$ {         add_header Content-Disposition "attachment; filename=$1";         alias "D:/apache-tomcat-7.0.32/webapps/upload/$1";    } Regular expressions are used here Formula to capture the requested file name. In addition, you need to pay attention to the location priority of nginx, first =, then ^~, and finally ~.




Basically, you need to add the following line in the location block of the URL you want to force download.

add_header Content-disposition "attachment; filename=$1";
default_type application/octet-stream;
The above two lines set the content-disposition header to "attachment" and the content-type to "application/octet-stream" to enable downloading .

Suppose, if you want to force download for all URLs starting with /downloads, then add the above line in the location block of the folder as shown below.

location /downloads {    ...    add_header Content-disposition "attachment; filename=$1";    default_type application/octet-stream;    ... } If you want to force downloads to certain file types and extensions (e.g. .jpg, .png, .mp3, etc.), add the above 2 lines in the location block for these file types.





location ~* ^/.+\.(?:gif|jpe?g|png|mp4|mp3)$ { ...    add_header    Content-disposition "attachment; filename=$1";    default_type application/octet-stream;    .. . } After the above modifications are completed, Nginx needs to be restarted or reloaded.





nginx -s reload

Guess you like

Origin blog.csdn.net/qq_42179736/article/details/131349249