【问题标题】:.htaccess Rewrite direct file access.htaccess 重写直接文件访问
【发布时间】:2012-07-23 20:30:12
【问题描述】:

我一直在寻找,但找不到适合我的解决方案。

我正在尝试重定向 http://example.com/files/file.ext -> http://example.com/users/documents/file.ext

无论我尝试什么,当我直接访问它下载的文件时。该文件的 GET 请求也没有显示在我的任何 apache 日志中。我已经登录调试了。

[编辑] 我要下载的文件有多种类型,包括 ppt、pdf、xls、zip、doc 等。我想将文件名重写到新 URI 的末尾。我也在使用 CodeIgniter,所以 /users/documents/ 是一个 RESTy uri。

有人解决了吗?

这是我的 .htaccess 文件:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    Options +FollowSymLinks
    RewriteBase /


    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php


    <IfModule mod_php5.c>
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [N]

        RewriteCond %{REQUEST_URI} ^/files/ [NC]
        RewriteRule ^/files/(.*)$ /users/documents/$1 [L,R=301]


    </IfModule>

    <IfModule !mod_php5.c>
        RewriteRule ^(.*)$ index.php?/$1 [L]
    </IfModule>

</IfModule>

【问题讨论】:

  • 您是否尝试过将/files/ 规则移到将所有内容重写为index.php 的规则之上?
  • 我刚试过。我以前有过,但没有那个确切的规则。它仍然只是下载文件。
  • “只是下载文件”是什么意思。它是 HTML 但未呈现吗?您是否为扩展名“.ext”分配了处理程序?
  • 是pdf、ppt、xls、zip、docx等多种文件类型,我想把被请求的文件放在新URI的末尾。

标签: .htaccess mod-rewrite


【解决方案1】:

如果这在您的 htaccess 文件中,请尝试替换此行:

RewriteRule ^/files/(.*)$ /users/documents/$1 [L,R=301]

与:

RewriteRule ^/?files/(.*)$ /users/documents/$1 [L,R=301]

并将条件和规则放在任何index.php 路由规则之前。

【讨论】:

  • 功能没有变化。我将条件和您修改后的重写规则移至“RewriteBase /”下方
  • @Scone 也许条件失败了? RewriteCond %{REQUEST_URI} ^/files/ [NC] 对我来说看起来不错,也许还可以将 ? 添加到前导斜杠(尽管它不应该需要它)所以它是 ^/?files/
  • 我会试试的。 '?' 是什么意思?做什么?
  • @Scone 表示/ 前面的? 是可选的
  • @Scone 好吧,您也可以尝试摆脱规则并使用 mod_alias:Redirect 301 /files /users/documents
【解决方案2】:

我去了http://martinmelin.se/rewrite-rule-tester/ 并测试了我的重写规则。 它说 RewriteCond 没有匹配任何东西,但是当我删除它匹配的规则时。

工作规则:

RewriteRule ^/?files/(.*)$ /users/documents/$1 [L,R=301]

将其移至 htaccess 文件的顶部可解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 2023-03-28
    • 2019-09-20
    相关资源
    最近更新 更多