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

Mac*_*ver 7 .htaccess mod-rewrite redirect

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

http://www.test.com/tag/bob%20hope
http://www.test.com/tag/bob%20hope%20is%20funny
Run Code Online (Sandbox Code Playgroud)

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

http://www.test.com/tag/bob-hope
http://www.test.com/tag/bob-hope-is-funny
Run Code Online (Sandbox Code Playgroud)

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

anu*_*ava 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]
Run Code Online (Sandbox Code Playgroud)

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

因此,一个URI的/tag/bob%20hope%20is%20funny将成为/tag/bob-hope-is-funny301

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

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

  • 感谢您添加说明!我每天都在Stack Overflow上学到一些新知识.:) (3认同)

Ste*_*man 5

基于 @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]
Run Code Online (Sandbox Code Playgroud)

我还添加了 N(下一个)参数,因为这会强制在该规则匹配时从头开始重新评估规则。如果不存在这一点,那么如果您使用 apache 作为反向代理,您可能会遇到问题,因为它不太可能在其他事情发生之前完成重写。