How can I make sure that Nginx serves plaintext files as a download, instead of inline?
I have Rails application (Redmine) which works with Nginx. If I am clicking on any attachment my browser (firefox, ie, chrome) ask me to download file. But if I am clicking on txt-type attachment my browser open this file in the browser.
As I understand it is task of Nginx to decide - open file in the browser or to download it. How can I setup it?
Default type for txt extension is text/plain. This behavior is described in mime.types file. Use http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type or http://nginx.org/en/docs/http/ngx_http_core_module.html#types to override it (maybe set to application/octet-stream).
Changing the Content-Type
of .txt
files may work, but it's a somewhat risky way to solve this problem, because you can't guarantee 100% that the user's browser will respond how you expect. And furthermore, it's misleading to label a .txt
file as a binary file.
Instead, I suggest using the standard way to force a browser to download rather than display the file, which is to use the Content-Disposition
header with a value of attachment
(RFC 2183, see also RFC 2616).
For example, this nginx location
block will send down such a header with .txt
files under the /downloads/
URI and thus they will be forced to download:
location ~ ^/downloads/.*\.txt$ {
add_header Content-Disposition "attachment";
}
So you could add other appropriate matching, etc, appropriate to your configuration.