【问题标题】:Add response header if the url ends with a specific snippet如果 url 以特定片段结尾,则添加响应标头
【发布时间】:2016-05-22 22:54:24
【问题描述】:

如果 url 以 mp3?dl 结尾,我想在响应中发送 Content-disposition "attachment" 标头。

我想在.htaccess 中这样做。

我试过了:

<FilesMatch ".mp3?dl$">
  Header set Content-disposition "attachment"
</FilesMatch>

有一个 WordPress 网站在 .htaccess 中添加了一些其他内容。如果我在文件末尾添加上面的这个 sn-p,它不会做任何改变。如果将其放在文件的顶部,则整个网站都会以服务器错误 (500) 结束。

要检查是否添加了标题,我使用curl:

$ curl -X HEAD -i 'http://example.com/files/audio/ping.mp3?dl'

HTTP/1.1 200 OK
Date: Sun, 22 May 2016 13:34:00 GMT
Server: Apache
Last-Modified: Sun, 22 May 2016 13:21:51 GMT
ETag: "12a...2"
Accept-Ranges: bytes
Content-Length: 76385
Content-Type: application/octet-stream

curl: (18) transfer closed with 76385 bytes remaining to read

如何在.htaccess 中执行此操作?

【问题讨论】:

    标签: php wordpress apache .htaccess


    【解决方案1】:

    FilesMatch 适用于文件,不能匹配查询字符串 (?dl)。

    要检查查询字符串,您通常使用 RewriteCondQUERY_STRING,但无法使用 mod_rewrite 设置标头,AFAIK。

    您可以在FilesMatch 中尝试If 并检查您想要的查询字符串,例如

    <FilesMatch "\.mp3$">
        <If %{QUERY_STRING} == "dl">
            Header set Content-disposition "attachment"
        </If>
    </FilesMatch>
    

    【讨论】:

      【解决方案2】:

      FilesMatch Directive 接受 regex 作为参数,因此您需要转义 .?,同时添加 .+ 以匹配任何文件名,即:

      <FilesMatch ".+\.mp3\?dl$">
        Header set Content-disposition "attachment"
      </FilesMatch>
      

      根据您的 cmets,您需要将 \? 更改为 \|

      <FilesMatch ".+\.mp3\|dl$">
        Header set Content-disposition "attachment"
      </FilesMatch>
      

      【讨论】:

      • 谢谢,但我已经尝试过了...它不起作用...可能是因为 Wordpress 的缘故吗?
      • 在正则表达式开头添加.+,检查更新。
      • 我也试过了,还是不行。我想问题出在匹配 url 时:如果我尝试为.* 设置自定义标头(例如X-Foo),那就可以了。
      • 我认为添加? 字符时会出现问题。 FilesMatch ".mp3" 工作正常。
      • 你能把?改成|吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2022-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多