Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In htaccess, I'd like to replace underscores with hyphens and then redirect the user the new url

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>
like image 272
Schoffelman Avatar asked Oct 04 '11 15:10

Schoffelman


1 Answers

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] 
like image 66
Shizzmo Avatar answered Oct 28 '22 23:10

Shizzmo