Mod rewrite 如何创建重写规则以在使用nginx下载时动态重命名PDF文件?

Mod rewrite 如何创建重写规则以在使用nginx下载时动态重命名PDF文件?,mod-rewrite,nginx,rewrite,Mod Rewrite,Nginx,Rewrite,我在允许用户下载PDF文件的网站上工作。 每个PDF文件都使用随机哈希名称存储在服务器上, 例如 现在,我可以尝试为用户提供文件的直接位置,但下载后的文件名显示为768E1F881783BD61583D64422279763A2A35B6804C.pdf,我想动态重命名该文件,我可以像这样使用php实现这一点 <?php // We'll be outputting a PDF header('Content-type: application/pdf'); // It will b

我在允许用户下载PDF文件的网站上工作。 每个PDF文件都使用随机哈希名称存储在服务器上, 例如

现在,我可以尝试为用户提供文件的直接位置,但下载后的文件名显示为768E1F881783BD61583D64422279763A2A35B6804C.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');
?> 
所以如果我把用户发送到这个位置

domain.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=this.is.test
然后我想在用户PC上下载这个文件,使用标题/文件名作为this.is.test.pdf

/usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf 
这只能使用
nginx
重写规则来完成吗?或者我也需要使用
PHP


更新1:

我试过这样使用它

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"'; 
}
但访问url时出现404未找到错误


更新2:

试过这个吗

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"'; 
}

仍然找不到404。

如果我没记错的话,你不能同时使用
别名
重写
。相反,只需使用location regex匹配,这些捕获将可用于
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;
}
这将与此URL匹配:

https://www.example.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=SamplePdf.pdf
并将其映射到此文件路径:

/usr/share/nginx/basesite/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf

注意:如果有人想让正则表达式不那么难看,那就去做吧

你差点就成功了。只要不需要
if
。只需
添加_头内容处理'附件;filename=“$arg_title.pdf””
@AlexeyTen需要更多信息,但仍然无法工作,如何拆分哈希,并获取创建子目录结构的前5个字符?感谢您的输入,刚刚测试过,它不工作,仍然没有找到404,我有办法调试这个吗?请忽略我最后的评论,它可以与.pdf扩展名一起工作,但不能与.png文件一起工作,为什么?有什么想法吗?好的,它工作得很好,有一个位置~*\.(?:png)${expires 7d;}规则,这导致了ISSUE,非常感谢。非常感谢。我将用简单的
(.)替换
([0-9a-fA-F])
。可能是重写而不是location@AlexeyTen,您可以将
重定向到
根目录之外的文件,还是需要声明
内部
https://www.example.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=SamplePdf.pdf
/usr/share/nginx/basesite/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf