i am working on site where i am allowing users to download PDF files. Each PDF file is stored on server using random hash names, eg.
file
768E1F881783BD61583D64422797632A35B6804C.pdf
is stored in
/usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf
now i can try to give users the direct location of file , but the file name after its being downloaded is shown as 768E1F881783BD61583D64422797632A35B6804C.pdf and i would like to rename the file on the fly, i can achive this using php like this
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
ref: Rename pdf file to be downloaded on fly
but i am lloking for something nginx rules directly which can rewrite download urls to path and rename too on the fly.
How can i do so ?
i have tried something like this.
location ^/download-pdf {
alias /usr/share/nginx/html/contents;
if ($request_filename ~ ^.*?/[^/]*?_(.*?\..*?)$)
{
set $filename $1;
}
add_header Content-Disposition 'attachment; filename=$filename';
}
so if i send user to this location
domain.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=this.is.test
then i want this file to be downloaded at users PC using title/filename as this.is.test.pdf
/usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf
can this be done only using nginx
rewrite rules ? or i need to use PHP
too ?
update1:
i have tried using it like this
location ^/download-pdf/([0-9A-F])/([0-9A-F])/([0-9A-F])/([0-9A-F])/([0-9A-F])/([0-9A-F]+).pdf$ {
alias /usr/share/nginx/basesite/html/contents;
add_header Content-Disposition 'attachment; filename="$arg_title.pdf"';
}
but the accessing url gives 404 not found error.
update2:
tried with this
location ~ /download-pdf {
alias /usr/share/nginx/html;
rewrite ^/download-pdf/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F]+).pdf$ /contents/$1/$2/$3/$4/$5/$6.pdf break;
add_header Content-Disposition 'attachment; filename="$arg_title.pdf"';
}
still getting 404 not found.