4

How to do this with regular expression?

Old -> New
http://www.example.com/cat1/cat2/cat3/tool-model-10   -> http://www.example.com/tool/tool-model-10
http://www.example.com/cat1/cat2/cat4/tool-model-11   -> http://www.example.com/tool/tool-model-11
http://www.example.com/cat1/cat2/tool-model-12        -> http://www.example.com/tool/tool-model-12
http://www.example.com/cat5/cat6/tool-model-13        -> http://www.example.com/tool/tool-model-13
http://www.example.com/cat7/tool-model-14             -> http://www.example.com/tool/tool-model-14

I've tried this:

Redirect 301 /cat1/cat2/cat3/tool-model-10 http://www.example.com/tool/tool-model-10
Redirect 301 /cat1/cat2/cat4/tool-model-11 http://www.example.com/tool/tool-model-11 
Redirect 301 /cat1/cat2/tool-model-12      http://www.example.com/tool/tool-model-12 
Redirect 301 /cat5/cat6/tool-model-13      http://www.example.com/tool/tool-model-13
Redirect 301 /cat7/tool-model-14           http://www.example.com/tool/tool-model-14

I understand that logiс should be:

  1. divide URL string on 2 strings: 1 and 2
  2. If first URL string 1 contains tool-model- at the end AND does not contain tool catalog at the beginning then make redirect to http://www.example.com/tool/tool-model- PLUS two digits (string 2).
MrWhite
  • 43,224
  • 4
  • 50
  • 90
Pretzel
  • 73
  • 4

1 Answers1

1

If first url string 1 contain "tool-model-" at the end AND does not contain "tool" catalog at the beginning make redirect to http://www.example.com/tool/tool-model- PLUS two digits (string 2)

To simplify/combine your redirects into a single ruleset I would use mod_rewrite, rather than mod_alias (Redirect or RedirectMatch) since you want a condition that says does not contain "tool" (which is tricky with RedirectMatch). Try something like the following in your root .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/tool/
RewriteRule /(tool-model-\d\d)$ /tool/$1 [R=302,L]

This states for any URL that ends /tool-model-NN and does not start /tool/ then redirect to /tool/tool-model-NN. $1 in the substitution is a backreference to the captured group (ie. (tool-model-\d\d)) in the RewriteRule pattern (a regex).

NB: I've used a 302 (temporary) redirect above. Change this to 301 (permanent) when you are sure it's working OK. 301 redirects are cached by the browser, so can make testing awkward. (So, you will need to clear your browser cache before testing the above directives.)

Also, if you are currently using mod_alias Redirect (or RedirectMatch) for other redirects then it would be advisable to also convert these to mod_rewrite RewriteRule directives. The reason being that different modules run at different times, regardless of the order in the .htaccess file. So, you can get some unexpected conflicts by combining redirects from both modules.

MrWhite
  • 43,224
  • 4
  • 50
  • 90