首页 文章

apache mod_rewrite:如何根据其他目录中的文件存在为同一目录添加不同的重写规则?

提问于
浏览
2

我目前在使用mod_rewrite的Apache 2.2服务器的.htaccess文件中配置重写规则时遇到了一些麻烦 . 这是我想要做的一般想法:

假设服务器域是example.com/,所有对example.com/abc/的请求和该目录下的路径都应该被重写 . 有两种情况:

  • 直接向example.com/abc/或example.com/abc/index.php请求将成为带有附加参数的example.com/index.php请求,以指示请求的原始目录 . 举几个例子:

  • example.com/abc/ ==> example.com/abc/index.php?directory=abc

  • example.com/abc/?foo=1&bar=2 ==> example.com/abc/index.php?directory=abc&foo=1&bar=2

  • example.com/abc/?a=b&c=d ==> example.com/abc/index.php?directory=abc&a=b&c=d

  • ......等等

  • 如果这些文件存在,example.com/abc/中的文件请求将成为对example.com/中文件的请求 . 指示当前目录的参数 . 举几个例子:

  • example.com/abc/image.png ==> example.com/image.png (如果以后的文件存在)

  • example.com/abc/sub/file.css ==> example.com/sub/file.css (如果以后的文件存在)

  • example.com/abc/foo/bar/baz/name.js ==> example.com/foo/bar/baz/name.js (如果以后的文件存在)

  • ......等等 .

我的.htaccess的内容目前看起来类似于:

RewriteEngine on
Options FollowSymLinks
RewriteBase /

# rule for files in abc/: map to files in root directory
RewriteCond $1 -f
RewriteRule ^abc/(.*?)$ $1

# rule for abc/index.php: map to index.php?directory=abc&...
RewriteCond $1 !-f
RewriteRule ^abc/(.*?)$ index.php?directory=abc&$1 [QSA]

后来的规则似乎有效,对example.com/abc/index.php的请求会按预期重写 . 但是,这不适用于abc /目录中的文件 . 关于我在这里做错了什么以及如何解决这个问题的任何提示都表示赞赏 . 必须对.htaccess进行哪些更改才能使所述内容正常工作?

1 回答

  • 0

    我找到了一个有效的解决方案:

    RewriteEngine on
    Options FollowSymLinks
    RewriteBase /
    
    # rule for file in abc/: map them to files in document root
    RewriteCond %{DOCUMENT_ROOT}/$1 -f
    RewriteRule ^abc/(.*?)$ %{DOCUMENT_ROOT}/$1 [L]
    
    # rule for abc/index.php: map to index.php?directory=abc&...
    RewriteRule ^abc/(.*?)$ %{DOCUMENT_ROOT}/index.php?directory=abc&$1 [QSA,L]
    

    两个主要区别是:

    • 使用 [L] 标志表示在规则匹配后不应考虑进一步的规则 - 这可能是为什么只有最后一条规则似乎有效的问题 .
      使用 %{DOCUMENT_ROOT} 在条件和重写位置
    • 前置位置以获取绝对路径 .

相关问题