NGINX: Force Pdf Files To Download & Not Open In Browser

The usual code for forcing pdf files to download and not open in the browser is this:

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

Restart the nginx server with the command:

service nginx restart 

It is best if the location directive is placed immediately after the server directive.

server {
	    server_name www.xyz.com;
	    return       301 http://xyz.com$request_uri;
location ~* /(.*\.pdf) {
    types { application/octet-stream .pdf; }
    default_type  application/octet-stream;
}

    	} 

If a location directive has been created for a folder (this is required for wordpress permalinks to work), the force pdf directive should be added there:

location /folder {
        try_files $uri $uri/ /news/index.php?q=$uri$is_args$args;
types { application/octet-stream .pdf; }
    default_type  application/octet-stream;
}

Basically, it is a hit-and-miss approach. Try various things till it works.

Update: By trial and error, I discovered that placing the directive after the “listen 80” port works.


server {
	    listen   80;
location ~* /(.*\.pdf) {
    types { application/octet-stream .pdf; }
    default_type  application/octet-stream;
}
// The rest of the directive continues

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *