htaccess redirect - replace special character
Question
In my previous post, I asked about how to 301 redirect all .com/language/X
URLs to .com/members/?members_search=X
using htaccess.
Thankfully I got help, and the solution was RewriteRule ^language/(.*) /members/?members_search=$1 [R=301,L]
I just discovered that I also need to convert any existing hyphens to spaces. I'm going to assume that there would be no more than 2 hyphens.
Test case
http://example.com/language/american-english
should 301 redirect to http://example.com/members/?members_search=american%20english
It's fine if an extra redirect is added, for example,
http://example.com/language/american-english
301 redirect to http://example.com/members/?members_search=american-english
which 301 redirects to http://example.com/members/?members_search=american%20english
Right under RewriteRule ^language/(.*) /members/?members_search=$1 [R=301,L]
, I've added this code, which is incorrect:
RewriteCond %{QUERY_STRING} members_search
RewriteRule ^(.*)-(.*)$ /$1\s$2 [L,R=301]
Please let me know if any ideas.
Solution
Try it like this, replacing your existing redirect (which is now the 2nd rule below):
# Repeatedly replace all hyphens with %20 - internally
RewriteRule ^language/(.*)-(.*) language/$1\%20$2 [N,DPI]
# Redirect to query string
RewriteRule ^language/(.*) /members/?members_search=$1 [NE,R=301,L]
This achieves the hyphen replacement and redirect to query string in just 1 external redirect. No additional redirect is required. Any number of hyphens are replaced.
This needs to go at the top of the .htaccess
file.
You will need to clear your browser cache. Test first with a 302 (temporary) redirect.
Additional notes:
language/$1\%20$2
- the%
needs to be backslash-escaped, otherwise%2
will be seen as an empty backreference, so you'd end up with0
instead of%20
.[N,DPI
] - TheN
causes the rewrite engine to immediately start over - creating a loop until all hyphens are replaced. TheDPI
flag is required to discard the original path-info (ie. the part after/language/
in the URL), otherwise this is re-appended (automatically) which could result in a rewrite loop.The
NE
flag is required on the second directive (the only change from your original rule) in order to prevent the%20
being doubly encoded as%2520
.