RewriteCond Pattern不扩展环境变量

时间:2015-01-20 20:12:00

标签: apache .htaccess mod-rewrite

尝试将所有请求发送到mydomain.com/downloads/*以运行download.php。因为这也可能是mydomain.com/some/path/downloads/*我需要从https://stackoverflow.com/a/21063276获取的动态RewriteBase但是当在RewriteCond模式中使用创建的Environment变量时它不起作用和日志显示原始%{ENV:BASE}而不是扩展变量。

.htaccess in domain.com/some/path:

RewriteEngine On
RewriteBase /

# Dynamic RewriteBase from https://stackoverflow.com/a/21063276
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

RewriteCond %{REQUEST_URI} ^%{ENV:BASE}/?download/(.*) [NC]
RewriteRule .* %{ENV:BASE}/download.php?file=%1&%{QUERY_STRING} [L]

重写日志:

(3) [perdir /var/www/123/some/path/] strip per-dir prefix: /var/www/123/some/path/download/file/225 -> download/file/225
(3) [perdir /var/www/123/some/path/] applying pattern '^(.*)$' to uri 'download/file/225'
(4) [perdir /var/www/123/some/path/] RewriteCond: input='/some/path/download/file/225::download/file/225' pattern='^(.*?/)(.*)::\\2$' => matched
(5) setting env variable 'BASE' to '/some/path/'
(3) [perdir /var/www/123/some/path/] add path info postfix: /var/www/123/some/path/download -> /var/www/123/some/path/download/file/225
(3) [perdir /var/www/123/some/path/] strip per-dir prefix: /var/www/123/some/path/download/file/225 -> download/file/225
(3) [perdir /var/www/123/some/path/] applying pattern '^(.*)$' to uri 'download/file/225'
(4) [perdir /var/www/123/some/path/] RewriteCond: input='/var/www/123/some/path/download' pattern='!-f' => matched
(4) [perdir /var/www/123/some/path/] RewriteCond: input='/some/path/download/file/225' pattern='^%{ENV:BASE}/?download/' [NC] => not-matched
(1) [perdir /var/www/123/some/path/] pass through /var/www/123/some/path/download

在第4行中正确设置了BASE,但是在第9行检查RewriteCond时它没有展开。如果它正在扩展,它应该可以正常工作。

有谁知道错误以及如何让它正常工作?

服务器版本:Apache / 2.2.15(Unix)

1 个答案:

答案 0 :(得分:2)

删除RewriteBase行并通过匹配RewriteRule中的模式修复第二条规则:

Options -MultiViews
RewriteEngine On

# Dynamic RewriteBase from http://stackoverflow.com/a/21063276
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^download/(.+) %{ENV:BASE}/download.php?file=$1 [L,QSA]