mod_rewrite:为什么不能使用环境变量来防止递归?

时间:2012-02-22 23:29:48

标签: mod-rewrite apache2

为什么我不能使用与此类似的mod_rewrite规则:

RewriteEngine On
RewriteCond %{ENV:did_rewrite} !=true
RewriteCond %{REQUEST_URI} ^(.*)/
RewriteRule (.*) %1/foo.php?original=$1 [E=did_rewrite:true]

防止递归?

当我调出RewriteLogLevel时,我看到了:

[.../initial] (3) [perdir /.../test/] strip per-dir prefix: /.../test/stuff -> stuff
[.../initial] (3) [perdir /.../test/] applying pattern '(.*)' to uri 'stuff'
[.../initial] (4) [perdir /.../test/] RewriteCond: input='' pattern='!=true' => matched
[.../initial] (4) [perdir /.../test/] RewriteCond: input='/test/stuff' pattern='(.*)/' => matched
[.../initial] (2) [perdir /.../test/] rewrite 'stuff' -> '/test/foo.php?original=stuff'
[.../initial] (5) setting env variable 'did_rewrite' to 'true'
[.../initial] (3) split uri=/test/foo.php?original=stuff -> uri=/test/foo.php, args=original=stuff
[.../initial] (1) [perdir /.../test/] internal redirect with /test/foo.php [INTERNAL REDIRECT]
[.../initial/redir#1] (3) [perdir /.../test/] strip per-dir prefix: /.../test/foo.php -> foo.php
[.../initial/redir#1] (3) [perdir /.../test/] applying pattern '(.*)' to uri 'foo.php'
[.../initial/redir#1] (4) [perdir /.../test/] RewriteCond: input='' pattern='!=true' => matched
[.../initial/redir#1] (4) [perdir /.../test/] RewriteCond: input='/test/foo.php' pattern='(.*)/' => matched
[.../initial/redir#1] (2) [perdir /.../test/] rewrite 'foo.php' -> '/test/foo.php?original=foo.php'
...

似乎,在"递归"呼叫,环境变量以某种方式变得不合适......但我无法弄清楚为什么会发生这种情况。

要清楚:我知道有很多方法可以阻止这种递归。我想了解为什么这种方式无效。

1 个答案:

答案 0 :(得分:7)

我认为this blog entry可能有你的答案。总之,当Apache执行内部重定向时,它renames all of the environment variables

static apr_table_t *rename_original_env(apr_pool_t *p, apr_table_t *t)
{
    const apr_array_header_t *env_arr = apr_table_elts(t);
    const apr_table_entry_t *elts = (const apr_table_entry_t *) env_arr->elts;
    apr_table_t *new = apr_table_make(p, env_arr->nalloc);
    int i;

    for (i = 0; i < env_arr->nelts; ++i) {
        if (!elts[i].key)
            continue;
        apr_table_setn(new, apr_pstrcat(p, "REDIRECT_", elts[i].key, NULL),
                  elts[i].val);
    }

    return new;
}

不幸的是,这似乎没有记录在任何地方。