Redirect 301 /search?q=avengers https://www.example.com/?s=avengers
You can’t match the query string with a mod_alias Redirect
(or RedirectMatch
) directive. The Redirect
directive matches the URL-path only. You need to use mod_rewrite and match against the QUERY_STRING
server variable.
For example:
RewriteCond %{QUERY_STRING} ^q=avengers$
RewriteRule ^search$ /?s=avengers [R=301,L]
This will need to go before the existing WordPress front-controller.
The slash prefix on the RewriteRule
pattern is intentionally omitted. ^search$
matches the URL-path /search
in a .htaccess
context.
However, since WordPress already uses mod_rewrite (front controller, etc.) you should really be using mod_rewrite for these redirects as well, rather than mod_alias. Different modules execute at different times during the request, so you can end up with unexpected conflicts. (You probably found that you could put the other Redirect
directives anywhere in the .htaccess
file and it still “worked” – this is not particularly intuitive.)
Have you try with RedirectMatch 301?
No, because I’m redirecting specific URLs, not patterns.
Aside: This argument doesn’t quite hold up. “Patterns” can match specific URLs (in fact, it can be easier to do so). The mod_rewrite directive above uses “patterns” (ie. regex) but matches only the exact URL you specified. In fact, Redirect
does not match “specific URLs” either – it is prefix matching (whole path segments), so you can find that a Redirect
is actually matching more than you thought it was!