301重定向将所有空格替换为连字符

时间:2011-04-28 15:31:59

标签: .htaccess mod-rewrite redirect

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

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

我为url slug添加了一个新字段,字符串用短划线替换了所有空格。虽然链接到这些新页面并获取数据没有问题,但我需要将旧URL重定向到新URL,这类似于:

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

因此,它需要能够考虑多个空格。任何问题? :)

2 个答案:

答案 0 :(得分:9)

在.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)替换为连字符-

因此/tag/bob%20hope%20is%20funny的URI将成为/tag/bob-hope-is-funny 301

简要说明:如果URI中有多个空格,则会以递归-递归替换每个空格字符,直到没有剩余空格为止,第一个RewriteRule被触发。此规则仅在内部重写。

一旦没有剩余空间,就会触发第二个RewriteRule,它只使用301 redirect转换后的URI。

答案 1 :(得分:2)

在@ anhubhava的答案的基础上,它已经关闭了,但它也会匹配URL中的%,2或0,如果你不这样做,它会导致apache 2.2循环使用DPI参数。完整的脚本应如下所示:

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(Next)参数,因此如果匹配则强制规则从此规则之后的直接开始重新评估。如果不存在这种情况,如果您将apache用作反向代理,则可能会出现问题,因为在其他情况发生之前,它不可能在重写结束时结束。

相关问题