Mod_rewrite underscores as dashes in URLs

At work I was faced with a problem — to rewrite all the URLs of a website that have underscores in, to dashes. This is to aid a painful transition to manage the website with the MODx php CMS.

Here is the mod_rewrite code that converts any underscores in an URL to dashes.

 # Rewrite underscores for dashes in URLs  – upto 6 underscores
RewriteCond %{REQUEST_URI} ^(.*)_(.*)/$
RewriteRule (.*)_(.*)/ http://www.microplop.com$1-$2/ [R=301]

RewriteCond %{REQUEST_URI} ^(.*)_(.*)_(.*)/$
RewriteRule (.*)_(.*)_(.*)/ http://www.microplop.com$1-$2-$3/ [R=301]

RewriteCond %{REQUEST_URI} ^(.*)_(.*)_(.*)_(.*)/$
RewriteRule (.*)_(.*)_(.*)_(.*)/ http://www.microplop.com$1-$2-$3-$4/ [R=301]

RewriteCond %{REQUEST_URI} ^(.*)_(.*)_(.*)_(.*)_(.*)/$
RewriteRule (.*)_(.*)_(.*)_(.*)_(.*)/ http://www.microplop.com$1-$2-$3-$4-$5/ [R=301]

RewriteCond %{REQUEST_URI} ^(.*)_(.*)_(.*)_(.*)_(.*)_(.*)/$
RewriteRule (.*)_(.*)_(.*)_(.*)_(.*)_(.*)/ http://www.www.microplop.com$1-$2-$3-$4-$5-$6/ [R=301]

RewriteCond %{REQUEST_URI} ^(.*)_(.*)_(.*)_(.*)_(.*)_(.*)_(.*)/$
RewriteRule (.*)_(.*)_(.*)_(.*)_(.*)_(.*)_(.*)/ http://www.microplop.com$1-$2-$3-$4-$5-$6-$7/ [R=301]
 

Hope this helps 

This entry was posted in Linux, Tips and tricks. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>