Skip to content

Instantly share code, notes, and snippets.

@un33k
Last active January 17, 2023 22:36
Show Gist options
  • 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;
}
}
@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