Sometimes you may need to force users to download content from your website instead of viewing it on their website. This is important in case your website has a lot of downloadable content. In this article, we will look at how to force download file in NGINX. Enforcing file downloads prevent users from streaming those files on your server and reduces server load for your website.
How to Force Download File in NGINX
Here are the steps to force download file in NGINX.
1. Open NGINX configuration file
Open terminal and run the following command to open NGINX configuration file. If your NGINX configuration file is located somewhere else, then please update the path below as per your requirement.
$ sudo vi /etc/nginx/nginx.conf
2. Force download file in NGINX
Basically, you need to add the following lines in the location block of URLs where you want to enforce downloads.
add_header Content-disposition "attachment; filename=$1";
default_type application/octet-stream;
The above two lines set the content disposition header to “Attachment” and content type to “application/octet-stream” to enable downloads.
For example, if you want to enforce downloads for all URLs starting with /downloads, then add the above lines in the location block for that folder, as shown below.
location /downloads { ... add_header Content-disposition "attachment; filename=$1";
default_type application/octet-stream;
... }
If you want to force downloads for all files ending with certain file types & extensions such as .jpg, .png, .mp3, etc. then add the above 2 lines in the location block meant for those file types.
location ~* ^/.+\.(?:gif|jpe?g|png|mp4|mp3)$ { ... add_header Content-disposition "attachment; filename=$1";
default_type application/octet-stream;
... }
3. Restart NGINX Server
Restart NGINX server to apply changes.
$ sudo service nginx restart
In this article, we have learnt how to force download files in NGINX. The key is to set both content-disposition as well as content-type headers for your response. In some cases, browsers look for content-disposition value and in other case it looks for content-type. So it is advisable to set both these headers to enable downloads.
This is really useful if you have many audio/video files on your website and you don’t want users to stream them on their browser. When you force users to download files the browser will quickly download files to their local machine and close the connection to your server. Otherwise, all users will be streaming files from your website, leading to too many open connections and increased server load on your website.
Also read:
How to List All Users in Ubuntu Linux
Apache Configure Multiple Virtual Hosts
How to Clean Up Disk Space in Linux
How to Add Response Header in NGINX
How to Redirect to Parent Folder in Apache
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.