Skip to content

Instantly share code, notes, and snippets.

@un33k
Last active January 17, 2023 22:36
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save un33k/7119264 to your computer and use it in GitHub Desktop.
Save un33k/7119264 to your computer and use it in GitHub Desktop.
Enable Nginx to send Content-Dispositions on specific files
server {
listen *:80;
server_name www.example.com;
rewrite ^(.*) http://example.com $1 permanent;
}
server {
listen *:80;
server_name example.com;
# Static directory
location /data/ {
autoindex on;
alias /data/;
expires 30d;
if ( $request_filename ~ "^.*/(.+\.(zip|tgz|iso|gz))$" ){
set $fname $1;
add_header Content-Disposition 'attachment; filename="$fname"';
}
}
root /srv/www/example.com;
access_log /srv/www/example.com/logs/access.log;
error_log /srv/www/example.com/logs/errors.log;
# Redirect server error pages to the static page /50x.html
error_page 500 502 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/www;
}
}
@garrison
Copy link

I believe your $request_filename should actually contain additional parentheses, like "^.*/(.+\.(zip|tgz|iso|gz))$". Otherwise it only matches zip files.

@huang-xiao-jian
Copy link

this really help me a lot, thanks very much

@tkchk
Copy link

tkchk commented Dec 8, 2018

used regex from @garrison comment

@Ravil86
Copy link

Ravil86 commented Apr 6, 2020

You must put a space after "if" :

if ( $request_filename ~ "^.*/(.+.(zip|tgz|iso|gz))$" ){
set $fname $1;
add_header Content-Disposition 'attachment; filename="$fname"';
}

@pooooriya
Copy link

its help me thank u so much

@un33k
Copy link
Author

un33k commented Dec 1, 2020

PRs are welcomed!

@rsgilbert
Copy link

You dont need to specify the filename. You can just do:

       location /attachments/ {
        add_header Content-Disposition 'attachment';
        proxy_pass http://localhost:8080/;
    }

@un33k
Copy link
Author

un33k commented Feb 4, 2022

@rsgilbert the filename is to pin down to only specified files of choice. Not all file types!

@araisch
Copy link

araisch commented Feb 10, 2022

Afaik you still don't need this complex filename stuff.

location /data/ {
        autoindex on;
        alias /data/;
        if ( $request_filename ~* .*\.(zip|tgz|iso|gz) ){
          add_header Content-disposition "attachment"; 
        }
      }

doing the same by decreased complexity (and note ~* for case insensitivity). Or am I wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment