301redirect将所有空格replace为连字符

所以这是我的问题。 我接手了一个网站,该网站有一大堆索引在Google中有%20的索引。 这是因为这个人决定只使用标签名称作为标题和url slug。 所以,url是这样的:

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

我已经添加了一个新的字段为urlslu and和stringreplace所有空格用破折号。 虽然链接到这些新页面并获取数据没有问题,但我需要将旧URLredirect到新URL,如下所示:

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

所以,它需要能够考虑多个空间。 任何问题? 🙂

在.htaccess文件中使用这些规则:

 Options +FollowSymlinks -MultiViews RewriteEngine on RewriteBase / # keep replacing space to hyphen until there is no space use internal rewrite RewriteRule ^([^\s%20]*)[\s%20]+(.*)$ $1-$2 [E=NOSPACE:1] # when there is no space make an external redirection RewriteCond %{ENV:NOSPACE} =1 RewriteRule ^([^\s%20]+)$ $1 [R=301,L] 

这会将所有空格字符( \s%20 )replace为连字符-

所以/tag/bob%20hope%20is%20funny会变成/tag/bob-hope-is-funny

简要说明:如果URI中有超过1个空格,则第一个RewriteRule会被recursion地用连字符replace每个空格字符-直到没有剩余空间为止。 这个规则只会在内部重写。

一旦没有剩余空间第二个RewriteRule被激发,只是使用301 redirect到转换后的URI。

build立在@ anhubhava的答案上,它是接近的,但是也会匹配URL中的%,2或0,并且如果不使用DPI参数,它可能导致apache 2.2上的循环。 完整的脚本应该是这样的:

 Options FollowSymlinks MultiViews RewriteEngine on RewriteBase / # keep replacing space to hyphen until there is no space use internal rewrite RewriteRule ^([^\s%20]*)(?:\s|%20)+(.*)$ $1-$2 [N,E=NOSPACE:1,DPI] # when there is no space make an external redirection RewriteCond %{ENV:NOSPACE} =1 RewriteRule ^([^\s%20]+)$ $1 [R=301,L] 

我还添加了N(下一个)参数,因此如果匹配的话,这将强制规则在开始后直接从头开始重新计算。 如果这不存在,那么如果将Apache用作反向代理,则可能会出现问题,因为在发生其他事情之前,它不太可能会重写。

我不知道这是否可行与mod_rewrite,因为它不会做replace。 看到这个线程: http : //www.webmasterworld.com/forum92/4423.htm

但是,只要将一点PHP添加到常用的头文件(如果有的话),就可以很容易地完成这个任务。