2014-11-04 62 views
2

我有一個網站,我有一個.htaccess文件與mod重寫,所以我的網址有點更好看,更多的搜索引擎優化友好。Mod Rewrite自動更新URL

RewriteEngine on 

RewriteCond %{HTTP_HOST} !^www\. 
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] 

ErrorDocument 404 /index.php?error=404 

RewriteRule ^(admin)($|/) - [L] 
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_]+)\.php$ index.php?country=$1 
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_A-Яа-я-]+)/([a-zA-Z0-9_-]+)\.php$ index.php?country=$1&id=$3 
RewriteRule ^([a-zA-Z0-9_-]+)/(.*)/(.*)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\.php$ index.php?country=$1&subid=$5&id=$4 
RewriteRule ^.+?---(.+)$ images/$1 [L,NE] 
Rewriterule ^sitemap.xml$ sitemap.php [L] 

正如你可以在上面的規則看,有「通配符」,這意味着在一些斜槓之間,任何事情都會發生。我使用它的方式是選擇語言並命名頁面的標題,以id變量結尾,以控制數據庫中表中的哪一行顯示。例如:

http://www.domain.com/en/heaters/hot-heater/26/60.php

以上URL包含域/的langugage /通配符/通配符/ id變量/ id變量

現在的問題是,當頁面上的鏈接得到由標題更新(假設熱水器的名稱改爲熱紅加熱器),谷歌索引的URL並不相同,並且這兩個URL仍然有效。

我想知道如何使用mod重寫來自動更新通配符到正確的標題。就像這裏在Stackoverflow上一樣,URL在URL中有這個問題的標題 - 如果我在URL中改變了這個,URL會自動將它改回原來的標題。這是如何完成的?

非常感謝提前。

回答

1

如果您需要具有像Stackoverflow URLs一樣的行爲,那麼您還需要一些服務器端支持(例如PHP)。考慮下面的代碼片段:

的.htaccess:

RewriteEngine On 
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?id=$1&title=$2 [L,QSA] 

的index.php:

<?php 
    $id = $_GET['id']; 
    $title = $_GET['title']; 

    $dbTitle = // get title by doing a database query using $id 
    // ... 

    if ($title != $dbTitle) { 
     // redirect with 301 to correct /<id>/<title> page 
     header ('HTTP/1.1 301 Moved Permanently'); 
     header('Location: /' . $id . '/' . $dbTitle); 
     exit; 
    } 
    // rest of your script 
?> 

這將支持URL像這樣即/id/some-title

+1

感謝@anabhava - 這實際上很有意義,我可以看到我如何實現這個並將其用作一個我編碼時的標準。再次感謝! – MazeyMazey 2014-11-07 20:38:36

+0

不客氣,很高興幫助。 – anubhava 2014-11-07 20:42:57