【问题标题】:mod_rewrite help to change Content-disposition based on URImod_rewrite 帮助根据 URI 更改 Content-disposition
【发布时间】:2010-11-28 13:15:40
【问题描述】:

我有一个 mp3 文件目录,希望能够内联地为它们提供服务,或者根据请求 URI 为用户提供下载选项。

/media/file1.mp3 -- 在这种情况下,我只想提供文件并让浏览器播放它。

/media/download/file1.mp3 -- 在这种情况下,我想让用户更轻松地下载文件。

我已经能够使用 mod_rewrite 和 php(使用 header() 和 readfile() 函数)来完成这项工作,但如果可能的话,我宁愿使用 mod_rewrite、mod_header 等来完成。

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    使用 mod_rewrite 您只能更改某些特定的标头字段,但 Content-Disposition 标头字段不属于这些字段。您只能更改 Content-Type 标头字段:

    RewriteRule ^media/[^/]+\.mp3$ - [L,T=audio/mpeg]
    RewriteRule ^media/download/[^/]+$ - [L,T=application/octet-stream]
    

    如果你想使用mod_headers+mod_setenvif 解决方案:

    SetEnvIf Request_URI ^/media/download/ force-download
    
    <IfDefine force-download>
        Header set Content-Disposition attachment
        Header set Content-Type application/octet-stream
    </IfDefine>
    

    【讨论】:

    • 谢谢。我一直在尝试这个不成功: SetEnvIF Request_URI "^/media/download" force-download=1 Header set Content-Disposition attachment env=force-download
    【解决方案2】:

    IfDefine 将检查在 Apache 启动时设置的变量,这样它就不起作用了。一个有效的配置是:

    SetEnvIf Request_URI ^/media/download/ force-download
    Header set Content-Disposition attachment env=force-download
    

    也不需要更改 Content-Type 来强制下载。

    【讨论】:

      【解决方案3】:

      如果你想基于 URI 中的参数规则,这里是逻辑/语法(适应 RewriteCond):

      RewriteCond %{QUERY_STRING} ^dl=1$
      RewriteRule ^ - [L,E=FORCEDOWNLOAD:1]
      Header set Content-Disposition attachment env=FORCEDOWNLOAD
      

      这里,如果唯一的参数是“dl=1”,我们强制下载

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多