Decoupling URLs from Rewrite Rules

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 http://shop.example.com. The customer would like to register brandname.com, otherbrandname.com 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
brandname.com        shop.example.com/brandname
otherbrandname.com shop.example.com/otherbrandname

After that you add to your vhost config:
<VirtualHost *:80>
    ServerName shop.example.com
    ServerAlias brandname.com otherbrandname.com

    [...]

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

Now if you redirect the brandname.com domain to the server at shop.example.com, apache looks up the HTTP_HOST (brandname.com) in map.txt.
Since You put it there, the URL gets rewritten to http://shop.example.com/brandname – the customer can now publish links to his brandname goods via http://brandname.com, 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.

Für neue Blogupdates anmelden:


Ein Gedanke zu “Decoupling URLs from Rewrite Rules

Schreibe einen Kommentar

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