Using RewriteMap Lookups in a RewriteCond . Possible?

Solution 1:

I've discovered that you cannot have a variable in the RewriteCond regex, because it seems it is only compiled once, but not per-request.

You could workaround this by putting both ${lookup} and %{REQUEST_URI} in a test string using a separator (let's say a comma) and then make sure they are equal, e.g :

RewriteCond %{REQUEST_URI},/${lookup:/$1/}/$2 ^([^,]+),\1

Also note that, for this given sample URL http://mydomain.dom/abc/mypage.html :

%{REQUEST_URI} = /abc/mypage.html

but

${lookup:$1} = abc

So %{REQUEST_URI} will never be equal to ${lookup:$1}.

To make them equal when requested, you have to :

  • enclose ${lookup:$1} with / to get /abc/ = /${lookup:$1}/
  • add $2 to also get the requested file : /abc/mypage.html = /${lookup:$1}/$2
  • As your key is /abc/ (and not abc) you need to enclode $1 with / to match the key : /${lookup:/$1/}/

So finally you will have this :

RewriteMap lookup "txt:/var/www/lookup.txt"
RewriteCond %{REQUEST_URI},/${lookup:/$1/}/$2 ^([^,]+),\1
RewriteRule ^/(.*)/(.*)$ /a/$1/b/$2 [R=301]

Going to http://mydomain.dom/abc/mypage.html gives me the following log :

(1) pass through /a/abc/b/mypage.html