.htaccess - 301 Redirect to replace all spaces to hyphens -


so here's problem. took on site has has bunch of pages indexed have %20 indexed in google. because person decided use tag name title , url slug. so, urls this:

http://www.test.com/tag/bob%20hope http://www.test.com/tag/bob%20hope%20is%20funny 

i have added new field url slug , string replaced spaces dashes. while have no problem linking these new pages , getting data, need 301 redirect old urls new urls, like:

http://www.test.com/tag/bob-hope http://www.test.com/tag/bob-hope-is-funny 

so, needs able account multiple spaces. questions? :)

use these rules in .htaccess file:

options +followsymlinks -multiviews rewriteengine on rewritebase /  # keep replacing space hyphen until there no space use internal rewrite rewriterule ^([^\s%20]*)[\s%20]+(.*)$ $1-$2 [e=nospace:1]  # when there no space make external redirection rewritecond %{env:nospace} =1 rewriterule ^([^\s%20]+)$ $1 [r=301,l] 

this replace space characters (\s or %20) hyphen -

so uri of /tag/bob%20hope%20is%20funny become /tag/bob-hope-is-funny 301

brief explanation: if there more 1 space in uri 1st rewriterule fired recursively replacing each space character hyphen - until there no space left. rule rewrite internally.

once no space left 2nd rewriterule fired uses 301 redirect converted uri.


Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -