N
N
Nikita2021-10-04 13:31:28
htaccess
Nikita, 2021-10-04 13:31:28

How to redirect with regular expression in htaccess?

Hello! There is a site on CMS ocStore 2.3. I need to make 301 redirects from these addresses:

https://site.ru/index.php?route=product/product&path=76&product_id=894/specification

to these addresses:
https://site.ru/index.php?route=product/product&path=76&product_id=894

Values ​​76, 894 vary depending on the category and product. Also, after product_id=894/ there can be any values.
Those. I need to redirect in all cases if there is some value after product_id=894.
Something like this:
Redirect 301 /index.php?route=product/product&path=[0-9]&product_id=[0-9]/[0-9 a-z] /index.php?route=product/product&path=[0-9]&product_id=[0-9]

But what is the right way to write it in htaccess?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Taran, 2021-10-04
@MrNix21

In theory it should have been like this

RewriteCond %{QUERY_STRING} (?:^|&)route\=product/product(?:$|&)
RewriteCond %{QUERY_STRING} (?:^|&)path\=([0-9]+)(?:$|&)
RewriteCond %{QUERY_STRING} (?:^|&)product_id\=([0-9]+)/specification(?:$|&)
RewriteRule ^index\.php$ /index.php?route=product/product&path=%1&product_id=%2 [L,R=301]

Where %1 and %2 are analogous to $1 and $2 from RewriteRule
, but the problem is that you have two requests and here you have to do it somehow differently because only $1 will work and it will be 894 since the groups from the previous cond will be erased.
so I think it can be done either through %{THE_REQUEST}
where you can select both parameters at once
. Well, or just put a regular expression in 404.php.
It will be even probably better, only to give 404 after the regular season and not before.
Here I described in more detail how to do it.
but the comrade says that it didn’t work for him, although everything worked for me on the test, read it in the comments I gave a more correct answer.
https://qna.habr.com/q/1041262#answer_2012466
if it doesn't work out, then write you will have to create a test stand;)

D
dodo512, 2021-10-05
@dodo512

if after product_id=894 there is some value

This product_id=[0-9]+[^0-9]or product_id=\d+\D
In the simplest case, if the parameters always go in exactly the same order, you can do this:
RewriteCond %{QUERY_STRING} ^(route=product/product&path=\d+&product_id=\d+)\D
RewriteRule ^index\.php$ /index.php?%1 [R=301,L]

If the parameters can be in any order.
RewriteCond &%{QUERY_STRING}& ^(?=.*&(route=product/product)&)(?=.*(&path=\d+)&)(?=.*(&product_id=\d+)[^&\d])
RewriteRule ^index\.php$ /index.php?%1%2%3 [R=301,L]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question