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 ^(.*)-(.*)$ /$1s$2 [L,R=301]
Please let me know if any ideas.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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%2will be seen as an empty backreference, so you’d end up with0instead of%20. -
[N,DPI] – TheNcauses the rewrite engine to immediately start over – creating a loop until all hyphens are replaced. TheDPIflag 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
NEflag is required on the second directive (the only change from your original rule) in order to prevent the%20being doubly encoded as%2520.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0