Decoupling URLs from Rewrite Rules

Avatar von Martin Brotzeller

Apache’s mod_rewrite is a really powerful tool, but with great power comes great responsibility. You wouldn’t like your customer to have to edit your rewriting rules.

The Objective

You have a customer who wants to sell goods at The customer would like to register, and so forth and redirect everything to the shopping site, but in addition he wants to map the brands with specific urls. The shopping software already has a fairly complicated SEO mechanism, based on the path, which you don’t want to disrupt.

You already concluded that mod_rewrite is the way to solve this.
You want the customer to be able to add in URLs on the fly, but you don’t trust him to not mess up the .htaccess with the rewrite rules.

The Solution

Apache has a nice feature for that purpose that seems to be a bit underused: rewrite maps.
A rewrite map is a data source that can be used as an associative array. Sadly, this cannot be put into your .htaccess since the RewriteMap command is usable in the server-config and vhost-config contexts only.
The Documentation clearly shows how you can create a file with your map and how you assign the file to a variable. Usage is not shown as clearly though.

So you first generate a map file that contains the mappings:

# brands we want to sell

After that you add to your vhost config:

<VirtualHost *:80>


    RewriteEngine On
    RewriteMap mymap txt:/path/to/map.txt
    RewriteCond %{HTTP_HOST} !^shop\.example\.com$ [NC]
    RewriteRule ^/?(.*) http://${mymap:%{HTTP_HOST}|}/$1 [L,R,NE]

Now if you redirect the domain to the server at, apache looks up the HTTP_HOST ( in map.txt.
Since You put it there, the URL gets rewritten to – the customer can now publish links to his brandname goods via, even allowing for
deep links into the brandname part of the shop.

You can put the map file at a place where the customer can edit it. If anything goes wrong with the map, a few links might be broken, but the shopping site itself is unaltered as long as the server config is not touched.

Avatar von Martin Brotzeller


Eine Antwort zu „Decoupling URLs from Rewrite Rules“

  1. Avatar von Dave S

    Useful stuff, thanks. I actually wasn’t familiar with RewriteMap at all. Now I’ll probably use it everywhere!

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Für das Handling unseres Newsletters nutzen wir den Dienst HubSpot. Mehr Informationen, insbesondere auch zu Deinem Widerrufsrecht, kannst Du jederzeit unserer Datenschutzerklärung entnehmen.