Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

.htaccess redirect all urls using %20 to -

I had a problem with duplicated urls, like:

/term/this-is-the-term
/term/this%20is%20the%20term

Which I already solved by making sure all the links use the - instead,

Now I want to redirect any indexed url with %20 so the problem disappears from Google webmasters (and is actually solved)

How can I redirect any url using %20 to - ?

I know basics of simple redirections but I smell this can only be achieved using a regex, which I am not so familiar with,

Any hint?

Upvotes: 2

Views: 4166

Answers (3)

Amir Mahmoodi
Amir Mahmoodi

Reputation: 100

I think the best way of doing this is:

Redirect 301 "/term/this is the term" "http://yourdomain.com/term/this-is-the-term"

Upvotes: 1

anubhava
anubhava

Reputation: 785276

Here is one single rule that will replace ALL the spaces with hyphens whether spaces are in query string OR in URI:

RewriteEngine On

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

Upvotes: 0

Jon Lin
Jon Lin

Reputation: 143906

Try:

RewriteEngine On
RewriteRule ^(.*)\ (.*)$ /$1-$2 [L,R=301]

That redirects anything with a space (%20) to use a dash instead. You'll need to put that rule before any other rules you have in the htaccess file in your document root (or in whatever directory you want this to apply to).

To have this apply to your query string (everything after the ?) you need to do something special:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.*)%20(.*)$
RewriteRule ^(.*)$ /$1?%1-%2 [L,R=301,NE]

Upvotes: 6

Related Questions