Skip to main content
Apache RewriteMap with MySQL

Apache RewriteMap with MySQL

Apache rewritemap is a wonderful addon for Apache that can directly connect to a datastore and pull data dynamically. So you don’t have to depend on a scripting language (like PHP, Python) to do the rewriting/redirect for you.
Our use case was to setup “Reverse proxy” to redirect request into different subdomains based on an input URI’s parameter value. Our subdomain data are stored in MySQL tables. This is what we have done to do that,

<VirtualHost *:80>
  RewriteEngine On
  DBDriver mysql
  DBDParams "host= host.localhost,user=admin,pass=password,dbname=someDB"
  RewriteMap data "dbd:select column from mytable where REPLACE(column,'www.','') = REPLACE(%s,'www.','')"
  RewriteCond ${data:%{HTTP_HOST}} ^\s*$
  #if we don't have match for the HOST, skip next rule as indicated
  RewriteRule ".?" "-" [S=1]
    #Else check for the matching records in our DB

    RewriteCond %{REQUEST_URI} ^/([^/]+)$
    RewriteMap myquery1 "dbd:select column from mytable where CONCAT(REPLACE(column,'www.',''),column2) = REPLACE(%s,'www.','')"
    RewriteCond  ${myquery1:%{HTTP_HOST}%1} ^(.+)$
    RewriteRule ^/(.*)$ https://%1/$1 [P,L]

    RewriteRule ^ - [F]


DBDriver and DBDParams are database connection settings. You may be supposed to enable rewrite map add-on, dbd plugin and install a suitable driver for this to work. 

sudo a2enmod dbd

sudo a2enmod rewrite_map

sudo apt-get install libaprutil1-dbd-mysql

a rewritemap directive can take one input which is being passed from RewriteCond here

RewriteCond ${data:%{HTTP_HOST}} ^\s*$

The host is passed to the RewriteMap and the result is checked to see if it has some data. If it does not then skip the next 3 rules. If it has, then the result of rewritemap query is fed into the RewriteRule as $1 though RewriteCond. The final one is to return forbidden. Do note, $1 variable generally represent the immediate parent data.

You could see “dbd” in the RewriteMap, it is a "MapType" param, which has another value “fastdbd”. “fastdbd” caches database query result until Apache server is restarted. We went with dbd since we have dynamic data flowing in.

You can explore other option of RewriteMap like file support from