![](/img/trans.png)
[英]Apache Rewrite (mod_rewrite) cannot rewrite, if directory name is same as another directory under root, such as “lib”, on Linux
[英]apache mod_rewrite: How to add different rewrite rules for same directory depending on file existence in other directory?
我目前在使用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进行哪些更改才能使内容按说明工作?
我找到了一个可行的解决方案:
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}
在条件和重写位置中添加位置前缀以获取绝对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.