How to Force a File To Download in NGINX


how to force file download nginx

Typically, when users access file (pdf, image, video) it tends to open in their browser. This can mean more resources consumed on your web server, since it has process it for the users. So it is advisable to force them to download the file, instead of opening in their browser. Let us take a look at how to force a file to download in NGINX.

 

How to Force a File To Download in NGINX

Here are the steps to force a file to download in NGINX.

 

1. Open NGINX config file

Open NGINX file in a text editor. You will typically find it at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Force a file to download

It’s easy to force a file to download in NGINX. You just have to add HTTP header “Content-Disposition” in location context. We will use the add_header module for this purpose.

Here are different use cases to force a file download.

 

If you want to force a download for a specific file type such as pdf across your website,


location ~* (.*\.pdf) {
add_header Content-disposition "attachment; filename=$1";
}

You can replace “pdf” with other file extensions as per your requirement.

 

If you want to force all jpg files in a directory (e.g /uploads) to download


location ~* /uploads/(.+\.jpg)$ {
add_header Content-disposition "attachment; filename=$1";
}

 

If you want to force all files in a directory to download


location ~* /uploads/.*$ {
add_header Content-disposition "attachment; filename=$1";
}

 

If the add_header directive doesn’t work for you, you can also try the above codes with types directive, as shown


location ~* (.*\.pdf) {
types { application/octet-stream .pdf; }
default_type application/octet-stream;
}

 

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! NGINX will force download of files on your website.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!