[英]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.