1

I'm working with a blog that has been around for a long time but was migrated to WordPress from a different platform recently. All of the old URLs are mapped to new permalinks via 301 redirects in .htaccess. Most of these redirects behave as expected, except for redirects that involve search queries. When redirecting a search query from the old the platform's structure to the WordPress structure, the redirect does not take effect and the user receives a 404. Normally, this wouldn't be of huge concern, but Google is crawling these and alerting in the client's search console.

So, for example, this produces expected results:

Redirect 301 /p/about-me.html https://www.example.com/about/

This, however, does not redirect and results in a 404:

Redirect 301 /search?q=avengers https://www.example.com/?s=avengers

Perhaps this has to do specifically with how WordPress is handling the query strings for searches, but it's not something that I've seen before.

Ideas?

  • Have you try with RedirectMatch 301? – Jevuska Jul 18 '17 at 1:29
  • No, because I'm redirecting specific URLs, not patterns. – DavidBrown Jul 19 '17 at 4:09
1
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!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.