Force file download with nginx
I have spend way too much time trying to figure out how to add a simple Content-Disposition response header for static files when the request URI contains a force_download GET parameter, except for hidden and PHP files. Sure I could pass the request to another (php) script, adjust the headers and back to nginx, but that doesn’t make sense as nginx already receives all required information and can do scripting. At last I built it and here it is for anyone’s sanity.
The idea is to use URLs with the special argument and it would download the file instead of viewing in the browser. The code below supports these combinations:
— What it does
- Extract the filename from the request path.
- Build the correct string when the request URI contains the
- Extract custom filename from the
- Clear the string when a hidden file is requested. (security)
- Reset the string when the header was already set by the backend, for example PHP.
- Then set the Content-Disposition header only when the status code is 200 (ok). When
$forceDownloadis empty the header is removed from the response.
Add this to your virtual host to force file download with nginx and have fun!
2015-01-11 – Replaced filename argument with inline regex
– changed order; backend headers rule
– cleaned up regexp
– added $filename at start to prevent error
– added filename argument