I'd like to redirect any request that contains underscores to the same url, but with hyphens replacing the urls. I've seen a lot of forums suggest I do something like this:
(Repeat an incremented version of this rewriteRule up to a gazillion)
rewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ http://example.com/$1-$2-$3-$4 [R=301,L]
rewriteRule ^([^_]*)_([^_]*)_(.*)$ http://example.com/$1-$2-$3 [R=301,L]
rewriteRule ^([^_]*)_(.*)$ http://example.com/$1-$2 [R=301,L]
My current solution in php is (which works fine):
if(preg_match('/[_]+/', $_SERVER['REQUEST_URI'])){
$redirectUrl = preg_replace('/[_]+/','-', $_SERVER['REQUEST_URI']);
header('Location: '. $redirectUrl , TRUE, 301);
return;
}
But, I'd rather not use php & instead keep it in my htaccess file without having to repeat that first rewriteRule over and over again in order to anticipate how many underscores each url might be. Thoughts? Is there such a way to do this with out repeating the incremented rewriteRule?
----- edit -----
My current htaccess file is just the standard WordPress one, which is below:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
See the "Next" directive/rewrite flag, which causes the ruleset to be reevaluated starting with the first rule: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_n
Something like this might work:
RewriteRule (.*)_(.*) $1-$2 [N]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With