2016-04-24 149 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-]+)