Zakalwe Zakalwe - 5 months ago 62
Apache Configuration Question

mod_rewrite - redirect to root and replace underscores with dashes

I have been agonising over this for a few hours - trying to get to grips with the syntax for mnod_rewrite, Basically, I am migrating a site so that urls like:


The two key things here are removing the "/news/article" bit and replacing underscores with dashes.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/?news/article$
RewriteRule ^([^_]*)_([^_]*_.*)$ $1-$2 [N]

RewriteCond %{REQUEST_URI} ^/news
RewriteRule ^([^_]*)_([^_]*)$ $1-$2 [N]

RewriteRule ^news/article/(.*)$ /$1 [L,R=301]

I can't seem to get the RewriteCond to fire. Please help!


You can do it like this:

RewriteEngine On

# remove /news/article/ when there is no _ left
RewriteRule ^news/article/([^_]+)$ /$1 [L,R=301,NC,NE]

# use recursion based rule to repalce _ by -
RewriteRule ^(news/article/[^_]*)_+(.*)$ $1-$2 [N,DPI]