blog-banner

Apache RewriteMap with MySQL

  • Debian
  • LINUX SERVER
  • Security
  • Ubuntu

Apache RewriteMap

 

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 set up a “Reverse proxy” to redirect requests 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,


  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 ^/(.*)$ http://%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 through RewriteCond. The final one is to return forbidden. Do note, $1 variable generally represents 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 results until the Apache server is restarted. We went with dbd since we have dynamic data flowing in.

You can explore other options of RewriteMap like file support from https://httpd.apache.org/docs/2.4/rewrite/rewritemap.html