Reputation: 781
I am trying to replace underscores with hyphens only on a particular parameter and then perform a 301 redirect. I have figured out how to replace them and apply it to the entire URL but cannot figure out how to replace them for just one paramater. Right now I have this:
RewriteCond %{QUERY_STRING} ^state=([a-zA-Z_]+)&city=([a-zA-Z_]+)$
RewriteRule city.html /find/this/in/%2/%1/? [L,R=301]
This 301 redirects this: mysite.com/city.html?state=va&city=dunn_loring
To this: mysite.com/find/this/in/dunn_loring/va/
I would like it to instead 301 redirect to this: mysite.com/find/this/in/dunn-loring/va/
Essentially I only want to replace underscores with hyphens for the '%1' portion in my htaccess example above. Thanks in advance for any pointers
Upvotes: 1
Views: 93
Reputation: 4800
The below solution works with no limit on the number on underscores. The first RewriteRule replaces the first underscore seen and the [N] flag causes processing to start over, so the rule will keep being applied until all the underscores are replaced. When no more underscores are left, the redirect is issued.
RewriteCond %{QUERY_STRING} ^state=([a-zA-Z_]+)&city=([a-zA-Z-]+)_([a-zA-Z_-]+)$
RewriteRule city.html /city.html?state=%1&city=%2-%3 [N]
RewriteCond %{QUERY_STRING} ^state=([a-zA-Z_]+)&city=([a-zA-Z-]+)$
RewriteRule city.html /find/this/in/%2/%1/? [L,R=301]
Upvotes: 2