301 重定向以将所有空格替换为连字符 [英] 301 Redirect to replace all spaces to hyphens
问题描述
所以这是我的问题.我接管了一个网站,该网站有一堆被索引的页面,其中有 %20 在 Google 中被索引.这仅仅是因为此人决定只使用标签名称作为标题和 url slug.所以,网址是这样的:
So here's my problem. I took over a site that has has a bunch of pages indexed that have %20 indexed in Google. This is simply because the person decided to just use the tag name as the title and url slug. So, the urls were something like this:
http://www.test.com/tag/bob%20hope
http://www.test.com/tag/bob%20hope%20is%20funny
我为 url slug 添加了一个新字段,字符串用破折号替换了所有空格.虽然链接到这些新页面并获取数据没有问题,但我需要 301 将旧 URL 重定向到新 URL,这将类似于:
I have added a new field for the url slug and string replaced all spaces with dashes. While I have no problem linking to these new pages and getting the data, I need to 301 redirect the old URLs to the new URLs, which would be something like:
http://www.test.com/tag/bob-hope
http://www.test.com/tag/bob-hope-is-funny
所以,它需要能够考虑多个空格.任何问题?:)
So, it needs to be able to account for multiple spaces. Any questions? :)
推荐答案
在您的 .htaccess 文件中使用这些规则:
Use these rules in your .htaccess file:
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
)替换为连字符 -
This will replace all space characters (\s
or %20
) to hyphen -
所以 /tag/bob%20hope%20is%20funny
的 URI 将变成 /tag/bob-hope-is-funny
和 301代码>
So a URI of /tag/bob%20hope%20is%20funny
will become /tag/bob-hope-is-funny
with 301
简要说明:如果 URI 中有 1 个以上的空格,则 1st RewriteRule 将被递归触发,用连字符 -
替换每个空格字符,直到没有空格为止.此规则只会在内部重写.
Brief Explanation: If there are more than 1 space in URI then 1st RewriteRule is fired recursively replacing each space character with hyphen -
until there is no space left. This rule will only rewrite internally.
一旦没有剩余空间,就会触发第二个 RewriteRule,它只使用 301 重定向
到转换后的 URI.
Once no space is left 2nd RewriteRule is fired which just uses a 301 redirect
to the converted URI.
这篇关于301 重定向以将所有空格替换为连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!