1

Trying to get all requests to mydomain.com/downloads/* to run through download.php. Because this could also be mydomain.com/some/path/downloads/* I need dynamic RewriteBase which I took from https://stackoverflow.com/a/21063276 however when using the created Environment variable in the RewriteCond pattern it doesn't work and the logs show the raw %{ENV:BASE} instead of expanding the variable.

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

Rewrite Log:

(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

BASE is set correctly in line 4, however it's not expanded when the RewriteCond is checked in Line 9. If it were being expanded it should work just fine from what I can tell.

Does anyone know what's wrong and how to get this to work correctly?

Server version: Apache/2.2.15 (Unix)

Community
  • 1
  • 1
Phoenix
  • 171
  • 2
  • 15

1 Answers1

2

Remove RewriteBase line and fix your 2nd rule by matching pattern in 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]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Thanks, that did the trick, didn't think about just matching in the rule. You should fix the %1 in the rule to $1 though, as otherwise the file parameter was empty for me. – Phoenix Jan 20 '15 at 22:12
  • Ah that's right, skipped changing it while fixing rules. Glad it worked. – anubhava Jan 20 '15 at 22:18