Search code examples
.htaccessseohttp-redirecthttp-status-code-301

how to redirect a bunch of files with htaccess


I have a site with a lot of url's like this

www.example.com/this_has_some_meaning.php

Now I learned that for SEO reasons it is better to use

www.example.com/this-has-some-meaning.php

Can i, using htaccess, redirect all the url's from the old to the new, using some kind of regex?


Solution

  • You can use these 2 rules in your .htaccess:

    RewriteEngine On
    
    # when there is only one underscore then redirect
    RewriteRule ^([^_]*)_+([^_]*)$ /$1-$2 [L,R=301,NE]
    
    # otherwise replace each _ by - recursively
    RewriteRule ^([^_]*)_+(.*)$ $1-$2 [N,DPI]