Search code examples
regexapachehttp-status-code-301http-redirect

How to redirect urls after deep level folder name change using rewrite rule


Our site spans across multiple languages (16 total), so the beginning of the url can contain 16 different subfolders. We have a subfolder beyond the lang/locale folder that has changed names so I am wondering how to redirect to the urls that involve the new subfolder name while also redirecting across the 16 different lang/locale subfolders?

Here is an example of the old and new urls:

Old urls:

www.something.com/en_US/product/family/parent/child.html www.something.com/ru_RU/product/family/parent/child/model.html

New urls:

www.something.com/en_US/product/family/parent/child2.html www.something.com/ru_RU/product/family/parent/child2/model.html


Solution

  • RewriteEngine On
    RewriteRule ^([a-zA-Z]{2}_[a-zA-Z]{2})/product/family/parent/([\w_]+)\.html$ /${1}/product/family/parent/${2}2.html
    RewriteRule ^([a-zA-Z]{2}_[a-zA-Z]{2})/product/family/parent/([\w_]+)/([\w_]+)\.html$ /${1}/product/family/parent/${2}2/${3}.html
    

    This may work for you, assuming that you're literally wanting to rename child_folder to child_folder2 (bikes -> bikes2, barbies -> barbies2, etc).

    If your goal is something more complicated (bikes -> bicycles, barbies -> dolls), that becomes something that needs to be handled through a server-side programming language, but htaccess can help. You can do something like

    RewriteEngine On
    RewriteRule ^([a-zA-Z]{2}_[a-zA-Z]{2})/product/family/parent/(child)\.html$ director.php?lang=${1}&old=${2}
    

    But you should avoid doing this if a straight regex solution is appropriate because there's no need to involve both and increase the load on your server when one is already involved.