htaccess: 301 redirect removing part of url

Viewed 234

I'm trying to move my shop from Shopify to Woocommerce. I have redirections 301 to do before moving my domain name. In order not to make the .htaccess file heavy, I would like to use regex to remove part from urls.

I would like to redirect

From:

https://"my-shop.com"/products/"product-name"

To:

https://"my-shop.com"/"product-name"

And

From:

https://"my-shop.com"/collections/"product-category-name"

To:

https://"my-shop.com"/"product-category-name"

So to remove "products" or "collections"

First problem: I absolutely don't know how to code that... I tried to understand by looking on the web, found some code, but it's too complicated for me, I did'nt success to adapt it to my problem. If I'm not wrong, to remove "products" for example, it would look like that:

RewriteEngine on
RewriteRule ^products/(.*)$ /$1 [R=301,L]

Second problem: If I changed a product name or product category, its url should not follow this rule but redirect to a totally different url. Can I still use regex for other products and product categories, but add a redirection 301 before so it could work for the product / category I modified?

1 Answers

Could you please try following. Following is looking for products OR collections keywords from URL.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(products|collections)/(.*)/?$ /$2 [NC,L]


OR use this rule in case you could have any string in place of products or collections.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/(.*)/?$ /$2 [NC,L]
Related