AMB*_*AMB 3 mod-rewrite rewrite nginx
我正在网站上工作,我允许用户下载PDF文件.每个PDF文件使用随机哈希名称存储在服务器上,例如.
file
768E1F881783BD61583D64422797632A35B6804C.pdf
is stored in
/usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf
Run Code Online (Sandbox Code Playgroud)
现在我可以尝试给用户直接位置的文件,但下载后的文件名显示为768E1F881783BD61583D64422797632A35B6804C.pdf,我想动态重命名文件,我可以使用这样的PHP来实现这个
<?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');
?>
Run Code Online (Sandbox Code Playgroud)
ref:重命名pdf文件以便在飞行中下载
但我正在直接购买nginx规则,可以将下载网址重写为路径并在运行时重命名.
我怎么能这样做?
我尝试过这样的事情.
location ^/download-pdf {
alias /usr/share/nginx/html/contents;
if ($request_filename ~ ^.*?/[^/]*?_(.*?\..*?)$)
{
set $filename $1;
}
add_header Content-Disposition 'attachment; filename=$filename';
}
Run Code Online (Sandbox Code Playgroud)
所以,如果我发送用户到这个位置
domain.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=this.is.test
Run Code Online (Sandbox Code Playgroud)
然后我希望使用标题/文件名作为this.is.test.pdf在用户PC上下载此文件
/usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf
Run Code Online (Sandbox Code Playgroud)
这可以仅使用nginx重写规则来完成吗?或者我也需要使用PHP?
UPDATE1:
我试过像这样使用它
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"';
}
Run Code Online (Sandbox Code Playgroud)
但访问URL给出404未找到错误.
UPDATE2:
试过这个
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"';
}
Run Code Online (Sandbox Code Playgroud)
仍然没有找到404.
Chr*_*aas 10
你不能同时使用alias和rewrite,如果我没有记错在一起.相反,只需使用位置正则表达式匹配,这些捕获将可用于add_header和alias指令:
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;
}
Run Code Online (Sandbox Code Playgroud)
这将匹配此网址:
https://www.example.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=SamplePdf.pdf
Run Code Online (Sandbox Code Playgroud)
并将其映射到此文件路径:
/usr/share/nginx/basesite/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf
Run Code Online (Sandbox Code Playgroud)
注意:如果有人想通过一切手段让那个正则表达式变得不那么难看!
| 归档时间: |
|
| 查看次数: |
2003 次 |
| 最近记录: |