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.

1 Answer 1


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 with 0 instead of %20.

  • [N,DPI] - The N causes the rewrite engine to immediately start over - creating a loop until all hyphens are replaced. The DPI 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.

  • 1
    PERFECT. Thanks so much again for the solution + helpful notes.
    – Jennifer
    Mar 9, 2021 at 23:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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