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:
product1234 travelbox_34 product1235 travelbox_13 product2310 case_07 product3126 case_12 product9320 anotheritem_54 .... ....
And save it to a folder you wish, eg
vim /etc/apache2/conf.d/productrewrites.txt
from this file, create a rewrite database, more info: httxt2dbm
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:
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:
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.
Hello,
Thanks for the article.
I wanna do a rewrite map for all the products of my website.
I would like to change https://www.domain.com/category/category/category/product-number.html
to
https://www.domain.com/product-number
How i could do that for all the products of my website ?
Cheers.
Don’t think you need a rewrite map for this… Something like:
RewriteEngine On
RewriteRule ^(.*)/(.*)/(.*)/(.*).html$ /$4 [L]
should work. (out of my head… you can test htaccess here)
you’ll probably need to add some excludes as well
Thanks for you reply.
It seems to work with the rules you give me, but how could i do if the products are https://domaine.com/category/product-number.html
Sometimes, it’s in juste one category, sometimes in two https://domaine.com/category/category/product-number.html or sometimes in 3 https://domaine.com/category/category/category/product-number.html
Could i write a rule whom working on all this ?
Do it will slow my website ? It is a better way than do a rewritemap ?
It’s a prestashop by the way.
Cheers.
Out of my head, try this:
RewriteEngine OnRewriteRule ^/(.+?)/?$ /$1 [L]
(.+?) is a regex (it’s called the non-greedy regex) and will capture everything until last optional regex is found , so the product-number.html in your case.
But, this might screw up more is not all subfolders in your uri are categories….