: .htaccess 301 redirect dynamic URL with regex? 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
How to do this with regular expression?
Old -> New www.example.com/cat1/cat2/cat3/tool-model-10 -> www.example.com/tool/tool-model-10 http://www.example.com/cat1/cat2/cat4/tool-model-11 -> www.example.com/tool/tool-model-11 http://www.example.com/cat1/cat2/tool-model-12 -> www.example.com/tool/tool-model-12 http://www.example.com/cat5/cat6/tool-model-13 -> www.example.com/tool/tool-model-13 http://www.example.com/cat7/tool-model-14 -> www.example.com/tool/tool-model-14
I've tried this:
Redirect 301 /cat1/cat2/cat3/tool-model-10 www.example.com/tool/tool-model-10 Redirect 301 /cat1/cat2/cat4/tool-model-11 www.example.com/tool/tool-model-11
Redirect 301 /cat1/cat2/tool-model-12 www.example.com/tool/tool-model-12
Redirect 301 /cat5/cat6/tool-model-13 www.example.com/tool/tool-model-13 Redirect 301 /cat7/tool-model-14 www.example.com/tool/tool-model-14
I understand that logiŃ should be:
divide URL string on 2 strings: 1 and 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 www.example.com/tool/tool-model- PLUS two digits (string 2).
More posts by @Michele947
1 Comments
Sorted by latest first Latest Oldest Best
If first url string 1 contain "tool-model-" at the end AND does not contain "tool" catalog at the beginning make redirect to 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-dd)$ /tool/ [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. in the substitution is a backreference to the captured group (ie. (tool-model-dd)) 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.
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2024 All Rights reserved.