为什么RewriteCond不能阻止RewriteRule处理?

时间:2012-03-02 16:15:51

标签: apache mod-rewrite httpd.conf

我在用于缓存清除js的.conf文件中有以下内容:

<Directory "/www/virtual/site/html/js/">
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^\d+\/(.+)$ $1 [L]
</Directory>

这里的想法是将site.com/js/123456/script.js重写为site.com/js/script.js

(重写工作正常)

如果我查看重写日志,我不理解的部分是它在内部重定向之后将RewriteRule应用于脚本... %{REQUEST_FILENAME} !-f不应该阻止它处理RewriteRule文件存在吗?

重写日志

[rid#2b607f8f2dc8/initial] (3) [perdir /www/virtual/site2/html/js/] add path info postfix: /www/virtual/site2/html/js/1234 -> /www/virtual/site2/html/js/1234/script.js
[rid#2b607f8f2dc8/initial] (3) [perdir /www/virtual/site2/html/js/] strip per-dir prefix: /www/virtual/site2/html/js/1234/script.js -> 1234/script.js
[rid#2b607f8f2dc8/initial] (3) [perdir /www/virtual/site2/html/js/] applying pattern '^\d+\/(.+)$' to uri '1234/script.js'
[rid#2b607f8f2dc8/initial] (2) [perdir /www/virtual/site2/html/js/] rewrite '1234/script.js' -> 'script.js'
[rid#2b607f8f2dc8/initial] (3) [perdir /www/virtual/site2/html/js/] add per-dir prefix: script.js -> /www/virtual/site2/html/js/script.js
[rid#2b607f8f2dc8/initial] (2) [perdir /www/virtual/site2/html/js/] strip document_root prefix: /www/virtual/site2/html/js/script.js -> /js/script.js
[rid#2b607f8f2dc8/initial] (1) [perdir /www/virtual/site2/html/js/] internal redirect with /js/script.js [INTERNAL REDIRECT]
[rid#2b6073eb14a8/initial/redir#1] (3) [perdir /www/virtual/site2/html/js/] strip per-dir prefix: /www/virtual/site2/html/js/script.js -> script.js
[rid#2b6073eb14a8/initial/redir#1] (3) [perdir /www/virtual/site2/html/js/] applying pattern '^\d+\/(.+)$' to uri 'script.js'
[rid#2b6073eb14a8/initial/redir#1] (1) [perdir /www/virtual/site2/html/js/] pass through /www/virtual/site2/html/js/script.js

1 个答案:

答案 0 :(得分:2)

mod_rewrite(按设计)继续应用重写规则,直到url不再更改。

因此,第二次尝试应用规则时,第一次将1234/script.js重写为script.js时,模式正则表达式不匹配,script.js被'传递'。

这是应该工作的方式。它有时可能是一种痛苦,但它使mod_rewrite更加强大/有用。

修改

在尝试应用RewriteRule之前,

mod_rewite首先测试RewriteCond模式。这样你就可以在你的RewriteCond中使用反向引用$ 0,$ 1等。在所有RewriteCond之后,它将创建替换字符串,因此它也可以使用反向引用%0,%1。等。另见下图。

因此,如果文件存在,它就会尝试在测试之前应用模式。

apache mod_rewrite flow