Korgano Crusher
Korgano Crusher

Reputation: 51

Replacing whitespaces in querystring with .htaccess

I have in Google hundreds if not thousands of URLs that have the name of the product in it. My new e-commerce now replaces the whitespaces with hyphens when constructs the URL and I need to make an .htaccess to automatically redirect the old URLs to the new ones by replacing the whitespaces with hyphens.

The example URL I'm using is

detalle.php?titulo=Zapatillas%20Salomon%20Xr%20Mission&codigo=040-8800-072

but the number of whitespaces to be replaces can vary widely.

The last iteration of rules that I have tried is:

RewriteCond %{QUERY_STRING} ^(.*)[\s|%20](.*)&codigo=(.*)
RewriteRule detalle.php detalle.php?%1-%2&codigo=%3 [N=20]

In a tester I found online this only replaces the last whitespace and let the others without change, in my development server not even that.

I have spent almost a day with this and going nowhere, even when acording to Apache documentation this should work.

Thanks in advance.

Edit:
The solution given by @anubhava

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*?)(?:\+|%20|\s)+(.+?)\sHTTP [NC]  
RewriteRule ^ /%1-%2 [L,NE,R=302]  

worked as requested, but somehow broke the lines in my .htacces that previously had been working perfectly (minus the whitespaces)

RewriteCond %{QUERY_STRING} ^titulo=(.*)&codigo=(.*)$
RewriteRule detalle.php http://otherdomain/%1--det--%2? [R=301,L]

this is to transform the URLs with parameters into "friendly" URLs.

Edit2:
There was some kind of problem in the development server because it was in a subdirectory, I tried it on the production server and everything worked fine so I'm accepting the answer. I put this edit just in case someone else have a similar situation.

Upvotes: 1

Views: 738

Answers (1)

anubhava
anubhava

Reputation: 785128

You can use this rule as first rule in your root .htaccess to convert all spaces by hyphens.

RewriteEngine In

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*?)(?:\+|%20|\s)+(.+?)\sHTTP [NC]
RewriteRule ^ /%1-%2 [L,NE,R=302]

Upvotes: 1

Related Questions