LXc LXc - 3 months ago 16
Apache Configuration Question

.htaccess regex replace dashes by underscore

For some reason a colleague replaced dashed by underscores in our website's URL.

I would like to 301 the old URLs to the new ones using a regex in our .htaccess

I found this code that works very well as intended, it is supposed to do the opposite, it replaces underscore with dashes :

RewriteEngine On
RewriteRule ^(/?articles/.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N]
RewriteRule ^(/?articles/.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301]


But for some reason i ignore why it does not work if i invert the logic

RewriteEngine On
RewriteRule ^(/?articles/.*/[^/]*?)-([^/]*?-[^/]*)$ $1_$2 [N]
RewriteRule ^(/?articles/.*/[^/]*?)-([^/-]*)$ $1_$2 [R=301]


Even if i escape the dashes, it won't work, any ideas or corrections are welcome

Answer

You can use these rules in your site root .htaccess with DPI flag:

RewriteEngine On

RewriteRule ^(articles/[^-]*)-+([^-]*-.*)$ $1_$2 [N,NC,DPI]

RewriteRule ^(articles/[^-]*)-([^-]*)$ /$1_$2 [NE,L,NC,R=301]

The DPI flag causes the PATH_INFO portion of the rewritten URI to be discarded.