How to create rewrite rule to Rename PDF file on the fly while Downloading using nginx? -
i working on site allowing users download pdf files. each pdf file stored on server using random hash names, eg.
file 768e1f881783bd61583d64422797632a35b6804c.pdf stored in /usr/share/nginx/html/contents/7/6/8/e/1/768e1f881783bd61583d64422797632a35b6804c.pdf
now can try give users direct location of file , file name after being downloaded shown 768e1f881783bd61583d64422797632a35b6804c.pdf , rename file on fly, can achive using php this
<?php // we'll outputting pdf header('content-type: application/pdf'); // called downloaded.pdf header('content-disposition: attachment; filename="downloaded.pdf"'); // pdf source in original.pdf readfile('original.pdf'); ?>
ref: rename pdf file downloaded on fly
but lloking nginx rules directly can rewrite download urls path , rename on fly.
how can ?
i have tried 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 send user location
domain.com/download-pdf/768e1f881783bd61583d64422797632a35b6804c.pdf?title=this.is.test
then want file downloaded @ users pc using title/filename this.is.test.pdf
/usr/share/nginx/html/contents/7/6/8/e/1/768e1f881783bd61583d64422797632a35b6804c.pdf
can done using nginx
rewrite rules ? or need use php
?
update1:
i have tried using
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 accessing url gives 404 not found error.
update2:
tried 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.
you can't use both alias
, rewrite
if remember correctly. instead, use location regex match , captures available both add_header
, alias
directives:
location ~* /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$ { add_header content-disposition 'attachment; filename="$arg_title"'; alias /usr/share/nginx/basesite/html/contents/$1/$2/$3/$4/$5/$1$2$3$4$5$6.pdf; }
this match url:
https://www.example.com/download-pdf/768e1f881783bd61583d64422797632a35b6804c.pdf?title=samplepdf.pdf
and map file path:
/usr/share/nginx/basesite/html/contents/7/6/8/e/1/768e1f881783bd61583d64422797632a35b6804c.pdf
note: if wants make regex less ugly means go it!
Comments
Post a Comment