加入收藏 | 设为首页 | 会员中心 | 我要投稿 商洛站长网 (https://www.0914zz.com/)- AI应用、CDN、边缘计算、云计算、物联网!
当前位置: 首页 > 运营中心 > Nginx > 正文

如何根据标题args C nginx重写动态更改文件名

发布时间:2023-12-12 13:48:44 所属栏目:Nginx 来源:DaWei
导读: 我正在使用nginx web服务器提供.pdf文件.并使用重写规则设置.pdf文件的文件名,具体取决于标题args.
我想要做的是,在文件名中添加我的域名example.com
1.如果title var包含example.com,则使用

我正在使用nginx web服务器提供.pdf文件.并使用重写规则设置.pdf文件的文件名,具体取决于标题args.

我想要做的是,在文件名中添加我的域名example.com

1.如果title var包含example.com,则使用title var data作为filename.

例如

URL : http://example.com/pdf/0D2E8C9DC2F732A6ACC6150811515F697E3C376C.pdf?title=[example.com]ebook Filename : [example.com]ebook.pdf

2.如果title var中不包含example.com,则将文件名设为[example.com] title var.pdf

例如

URL : http://example.com/pdf/0D2E8C9DC2F732A6ACC6150811515F697E3C376C.pdf?title=ebook Filename : [example.com]ebook.pdf

3.如果未设置title,则使用filename作为[example.com] hash.pdf文件名.

例如

URL : http://example.com/pdf/0D2E8C9DC2F732A6ACC6150811515F697E3C376C.pdf Filename : [example.com]0D2E8C9DC2F732A6ACC6150811515F697E3C376C.pdf

我怎样才能实现这样的目标. ?

我当前的配置看起来像这样

#pdf download block location ~* /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${ #if title is not set then use hash.pdf as filename if ( $arg_title = '' ) { add_header Content-Disposition 'attachment; filename="[example.com]$1$2$3$4$5$6.pdf"'; } add_header Content-Disposition 'attachment; filename="[example.com]$arg_title.pdf"'; alias /var/www/example.com/pdf/$1/$2/$3/$4/$5/$1$2$3$4$5$6.pdf; expires 1y; }

上面的代码只有在没有设置title var的情况下才能正常工作,但如果我将title var设置为[example.com] ebook.pdf,它会再次添加域名,最终的文件名变为

[example.com][example.com]ebook.pdf 据我所知,我们可以假设如果在$arg_title变量的开头有一个[example.com]子字符串,我们可以安全地将其删除.
所以这是你需要的配置:

location ~* /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${ #First of all we should put pdf path from the request into a variable,#since $1,$2,$n would contain other data later: set $hashpath $1/$2/$3/$4/$5/$1$2$3$4$5$6; #Same applies to hash title: set $hashtitle $1$2$3$4$5$6; #Now we try to get the title argument without getting [example.com] in the beginning: if ( $arg_title ~ "^([example.com])?(.*)$") { #This way if title contained [example.com],it would go to $1 variable,while $2 has our new cleaned title: set $pdftitle $2; } #now we check if title was empty: if ( $arg_title = '' ) { #and assign our title that $hashtitle variable we got from the request earlier: set $pdftitle $hashtitle; } #also we check if title has only [example.com] without anything else: if ( $arg_title = '[example.com]' ) { set $pdftitle $hashtitle; } #After that we can safely put [example.com] in front of our filename,without worrying that there would be a double: add_header Content-Disposition 'attachment; filename="[example.com]$pdftitle.pdf"'; alias /var/www/example.com/pdf/$hashpath.pdf; expires 1y; }

适用于nginx 1.9.12这里:

title=[example.com]test

title=just_test

title is not set

实际文件位于here

(编辑:商洛站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章