How to fix redirection for query?

I have old and new URL paths, I want to write redirection rules, so 2 versions of old paths with query strings:

/cgi-bin/something?123
/cgi-bin/something?keywords=123&offset=120

are both redirected to new path:

/catalogsearch/advanced/result/?something[]=789

Here are 2 rules I wrote (I use mapping files to make id resolving 123 -> 789)

RewriteCond %{REQUEST_URI} /cgi-bin/something?
RewriteCond %{QUERY_STRING} ^([0-9]{1,})$
RewriteRule "^cgi-bin/something?"   "/catalogsearch/advanced/result/?something\[\]=${something:%1|NOTFOUND}" [R=307,L]

RewriteCond %{REQUEST_URI} /cgi-bin/something?
RewriteCond %{QUERY_STRING} ^keywords=([0-9]{1,})$
RewriteRule "^cgi-bin/something?"   "/catalogsearch/advanced/result/?something\[\]=${something:%1|NOTFOUND}" [R=307,L]

The first part is for the first version of the path, the second for other (with keywords). The first works fine, second seems not to match for the query string.

How to fix it?


For your second rewrite expression

RewriteCond %{REQUEST_URI} /cgi-bin/something?
RewriteCond %{QUERY_STRING} ^keywords=([0-9]{1,})$

This matches will match the string

/cgi-bin/something?keywords=123

But will not match

/cgi-bin/something?keywords=123&offset=120

The regex you are using ^keywords=([0-9]{1,})$ has a dollar sign ($) saying that after the group consisting of 1 or more numbers from 0 through 9, the end of the line is immediately afterwards.

The &offset=120 part at the end of the URI causes the role not to match.

You can change the regex as follows, which will adds zero or more characters after the group of numbers before the end of the line. However, that may not be exactly what you want either. It depends on what URLs you want rewritten. Determine what you want matched afterwards (do you want the '&offset'?) and modify your regular expression accordingly.

RewriteCond %{QUERY_STRING} ^keywords=([0-9]{1,}).*$

PS - I find this website useful for visualizing regular expressions.