Today I needed to rewrite a list of about 1000 URL’s to a new location. Our product database was cleaned and new URL’s were created… Using RewriteMap from Apache’s Mod_rewrite comes in handy here.
In my case I needed to rewrite URL’s like this:
www.exampledomain.com/en/product1234/product_detail.php
to
www.exampledomain.com/en/travelbox_12/product_detail.php
Where in my URL’s I had a 1000 different ‘poducts1234’ to rewrite to a new URL.
Here’s the HOWTO:
Create a textfile on your server with 2 columns. Something that would look like this:
1 2 3 4 5 6 7 |
product1234 travelbox_34 product1235 travelbox_13 product2310 case_07 product3126 case_12 product9320 anotheritem_54 .... .... |
And save it to a folder you wish, eg
1 |
vim /etc/apache2/conf.d/productrewrites.txt |
from this file, create a rewrite database, more info: httxt2dbm
1 |
httxt2dbm -f db -i /etc/apache2/conf.d/productrewrites.txt -o /etc/apache2/conf.d/productrewrites.db |
Once done, open your vhosts config and add the following configuration:
1 2 3 4 |
RewriteEngine On RewriteMap rewrites dbm=db:/etc/apache2/conf.d/productrewrites.db RewriteCond {rewrites:$1} !="" RewriteRule ^/(.*)/(.*)/(.*)$ http://www.exampledomain.com/(.*)/${rewrites:$1}/$2? [R=permanent,L] |
A bit of clarification:
The line with content:
1 |
RewriteCond {rewrites:$1} !="" |
creates a condition that if the rewritemap contains the URI and the value is not “” (so an empty string) then it should perform the RewriteRule
.
The rewrite rule itself is pretty obvious. It’ll rewrite the URL’s for which the rewritemap is found to the new product URL, and also keep the trailing parameters.