I'm using Apache2 and mod_rewrite to hide my query strings. These are the rules in question.
RewriteCond %{QUERY_STRING} ^query=(.*)$
RewriteRule (.*) /search/%1 [R=301,L]
RewriteRule ^search\/?$ /search/?query=test [R=301,L]
When I visit /search
(or /search/
) I am correctly redirected to /search/?query=test
(as per the last rule)
From there, the RewriteCond
and RewriteRule
should kick in and redirect me to /search/test
, right? From what I understand the %1
in my first RewriteRule
corresponds to the (.*)
in the RewriteCond
which should contain test
.
However, what actually happens is I'm redirected to /search/test/?query=test
. So, the rule works, but for some reason the query string appended. Is it the QSA option being automatically added somehow/somewhere?
I'm then stuck in an infinite loop of redirecting to /search/test?query=test
because the first RewriteCond
and RewriteRule
kick in again, and again, and again...
What am I doing wrong?!
Thanks!
You need to specify an empty query in the substitution to prevent the original requested query to be appended to the new URL:
Modifying the Query String
By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the [QSA] flag.
So:
RewriteCond %{QUERY_STRING} ^query=(.*)$
RewriteRule (.*) /search/%1? [R=301,L]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With