.htaccess 302使用正则表达式替换重定向

时间:2014-11-24 00:52:15

标签: regex .htaccess seo

我有搜索网站,用户在网址中输入以下查询并进行搜索。

http://www.example.com/?search=key word&type=sin
http://www.example.com/?search=key word

我正在页面中进行规范链接,以避免将这些链接编入索引。

<link rel="canonical" href="http://www.example.com/key-word/"/>

但是我需要添加302重定向到此。即

Redirect 302 / http://www.example.com/key-word/ (key word is replaced spaces to hypen)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在DOCUMENT_ROOT/.htaccess文件中使用此代码:

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+(?:index\.php)?\?search=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]

## replace of space with -

# executes **repeatedly** as long as there are more than 1 spaces in URI
RewriteRule "^(\S*) +(\S* .*)$" /$1-$2 [L,NE]

# executes when there is exactly 1 space in URI
RewriteRule "^(\S*) (\S*)$" /$1-$2? [L,R=302,NE]