Home » Php » php – In htaccess, I'd like to replace underscores with hyphens and then redirect the user the new url

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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>
How to&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] 

Answer:

How about combining the 2. Have a single rewrite rule that rewrites to a PHP script that does the substitution and redirect. That way you avoid having multiple rewrite rules, can handle any number of underscores and only invoke the PHP redirection when it is needed.