Group parent categories from url

I am trying to fix a problem with 301 redirects and htaccess. I moved the site from the old domain to the new one. And I successfully dealt with 301 redirects. Thus:

Redirect 301 / https://newdomain.com 

On the old child categories of the page, the URLs look like this:

 olddomain.com/product-category/parent-cat1/parent-cat2/child-cat 

or

 olddomain.com/product-category/parent-cat1/child-cat 

or

 olddomain.com/product-category/child-cat 

While on the new site they are:

 newdomain.com/product-category/child-cat 

Unfortunately, this results in 404s of redirects. Is there a way to remove parent categories (which may differ in name and quantity) from the URL?

Thanks in advance for any advice, greetings

+7
.htaccess
source share
1 answer

Try to include the following RedirectMatch directive before the existing Redirect directive:

 RedirectMatch 302 ^/([\w-]+)/(?:[\w-]+/)+([\w-]+)$ https://newdomain.com/$1/$2 

The RedirectMatch directive complements the RedirectMatch directive as part of mod_alias. In addition, the RedirectMatch directive uses a regular expression to match a URL, while Redirect uses simple prefix matching.

This assumes that the path segments (for example, "product category", "parent cat" and "daughter cat") consist only of the characters az , az , 0-9 , _ and - (hyphen). This should be as specific as possible so that there is no β€œtoo much”. One or more "parent cats" are required.

$1 is a backlink to the first captured group in the template. i.e. ([\w-]+) , product category. And $2 is a backlink to the second captured group, i.e. ([\w-]+) at the end of the picture, child-cat. The group (?:....) "in the middle is a group that is not associated with the capture, so there is no backlink for this.

This is a 302 (temporary) call forwarding. Change it to 301 only when it is working properly. Testing with 302s is easier because the browser is not cached by the browser. Therefore, before testing, you must ensure that the browser cache is clear.

+6
source share

All Articles