How to Force File Downloads with NGINX: Step-by-Step Configuration Guide
This guide explains why and how to configure NGINX to force browsers to download files instead of displaying them, covering simple header settings, regex‑based filename handling, location priority rules, and the necessary reload command.
Why Force File Downloads?
Sometimes you need to force users to download content from your site rather than view it in the browser, especially when you have many downloadable resources. Forcing downloads prevents streaming, reduces server load, and ensures users receive the intended file.
Browser Default Behavior
Modern browsers can recognize many file types (txt, pdf, jpg, etc.) and automatically open them.
Case 1: Simple Attachment Header
Adding the
Content‑Disposition: attachment;header makes the browser download the file.
# Inline display (browser shows the file)
Content‑Disposition: inline; filename=foobar.pdf
# Forced download (e.g., Firefox)
Content‑Disposition: attachment; filename=foobar.pdfNGINX configuration example:
location /download {
add_header Content‑Disposition "attachment;";
}Case 2: Preserve Original Filename and Handle IE Issues
For image or PDF links, you may want the browser to prompt a save dialog using the original filename. IE may ignore the header if the MIME type is changed, so the
filenameparameter is essential.
Solution: add
Content‑Disposition: attachment; filename=yourfilein the response header.
location ~ ^/somepath/(.*)$ {
add_header Content‑Disposition "attachment; filename=$1";
alias "E:/apache-tomcat-7.0.32/webapps/upload/$1";
}Note: NGINX location priority is
=, then
^~, and finally
~.
General Settings for Forced Downloads
add_header Content‑Disposition "attachment; filename=$1";
default_type application/octet-stream;Examples
Force download for all URLs under
/downloads:
location /downloads {
...
add_header Content‑Disposition "attachment; filename=$1";
default_type application/octet-stream;
...
}Force download for specific file extensions (e.g., .jpg, .png, .mp3):
location ~* ^/.+\.(?:gif|jpe?g|png|mp4|mp3)$ {
...
add_header Content‑Disposition "attachment; filename=$1";
default_type application/octet-stream;
...
}Apply Changes
After editing the configuration, reload NGINX to apply the changes:
nginx -s reloadOpen Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.