Redirect All Search Links Containing – to + on WordPress
You can do something like the following at the top of your .htaccess
file to replace all -
with +
that occur after the /search/
path segment in the requested URL:
RewriteRule ^(search/[^-]*)-([^-]*-.*) /$1+$2 [N]
RewriteRule ^(search/[^-]*)-([^-]*)$ /$1+$2 [R=302,L]
The first RewriteRule
loops (internally) until all except 1 hyphen has been replaced with +
. The second RewriteRule
triggers an external redirect, replacing the last hyphen. In your example, where there is only 1 hyphen then the redirect will occur immediately.
Change the 302 (temporary) redirect to 301 (permanent) – if that is the intention – only after you have tested that it works OK.
UPDATE: If you have a problem with a rewrite loop (and consequently no redirect) when there are multiple hyphens (-
) in the requested URL then you probably have an issue with PATH_INFO being appended to the target URL on each iteration of the loop. This can be fixed with the DPI
(Discard Path Info) flag on the first RewriteRule
directive. For example:
RewriteRule ^(search/[^-]*)-([^-]*-.*) $1+$2 [N,DPI]
RewriteRule ^(search/[^-]*)-([^-]*)$ /$1+$2 [R=302,L]
The slash prefix on the first RewriteRule
substitution is then not required.