2016-04-24 151 views
1

我的网址有问题。url重定向从_到 - htaccess

这是我的htaccess的代码:

RewriteRule ^music-(.*)-([0-9_]+)\.html$ /artiste.php?g=$1&page=$2 [NC,L] 

所以在谷歌或Bing一些URL可以显示这样music_(.*)_([0-9_]+)\.html 如果可能的话我想改变_-与htaccess的。

我想_任何网址更改为-,因为所有环节的工作与正确,但-在我的研究一些网址_,所以我想用-替换它们。 例如:

错误:http://www.example.com/me_like_this.html 正确:http://www.example.com/me-like-this.html

回答

0
RewriteEngine On 
RewriteRule ^(.*)_(.*)$ /$1-$2 [L,R=301] 
RewriteRule ^music-(.*)-([0-9_]+)\.html$ /artiste.php?g=$1&page=$2 [NC,L] 

请试试这个。

+2

问题在于浏览器必须多次重定向,直到所有下划线消失。最好在内部进行转换。 –

1

您可以使用您的/.htaccess文件中的以下内容:

RewriteEngine On 

# Replace underscores with hyphens, set the environment variable, 
# and restart the rewriting process. This essentially loops 
# until all underscores have been converted to hyphens. 

RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=underscore:yes,N] 

# Then, once that is done, check if the underscore variable has 
# been set and, if so, redirect to the new URI. This process ensures 
# that the URI is rewritten in a loop *internally* so as to avoid 
# multiple browser redirects. 

RewriteCond %{ENV:underscore} yes 
RewriteRule (.*) /$1 [R=302,L] 

然后在后面加上您的规则:

RewriteRule ^music-(.+)-(\d+).html$ /artiste.php?g=$1&page=$2 [NC,L] 

如果这是为你工作,你想使浏览器和搜索引擎缓存的重定向,将302更改为301

注:在你RewriteRule我已经改变.*.+所以它只匹配一个或多个字符,而不是零个或多个字符。此外,我已将[0-9_]+更改为\d+,这是不包含下划线的等效速记,无论如何都将其转换为连字符。如果要在最后一个捕获组中包含连字符,请将(\d+)更改为([\d-]+)