2012-06-12 45 views
1

我需要重寫從網址:有沒有辦法重寫這個URL?

www.example.com/John.Connor/my-first-post/42 

到:

www.example.com/post.php?postid=42&userid=19 

表:

USER: 
id, name, surname, email, password 

POST: 
id, title, post, userid 

有沒有辦法做到這一點?

+0

你確定你不想要它嗎? –

+0

對不起,是的,我想要另一種方式。我只是正確的:D – xRobot

回答

1

那麼mod_rewrite無法查詢您的數據庫,因此它不能通過.htaccess本身完成。你可以做的就是有這個規則在.htaccess:

啓用mod_rewrite的,並通過httpd.conf的.htaccess,然後把這個代碼在你.htaccessDOCUMENT_ROOT目錄:

Options +FollowSymLinks -MultiViews 
# Turn mod_rewrite on 
RewriteEngine On 
RewriteBase/

RewriteRule ^[^/]+/[^/]+/([0-9]+)/?$ post.php?postid=42 [L,QSA] 

然後你post.php腳本中有代碼像這樣:

$postid = mysql_real_escape_string($_GET['postid']); 
$userid = mysql_real_escape_string($_GET['userid']); 

if (empty($userid)) { 
    $userid = mysql_result(mysql_query("SELECT userid FROM POST WHERE id=$posid"), 
       0, "userid"); 
    // now redirect by appending &userid=49 in the current URL 
    header("Location: " . $_SERVER["REQUEST_URI"] . "&userid=" . $userid); 
    exit; 
} 
+0

偉大的解決方案,但如果htaccess無法查詢數據庫,那麼像pinterest這樣的網站如何具有這樣的URL:http://pinterest.com/robingood/wow-collection/(robingood是用戶名和哇,集合是類別)? – xRobot

+0

@xRobot:即使有這樣的URL方案。例如這個問題有這個URL:'http:// stackoverflow.com/questions/10992072/is-there-a-way-to-rewrite-this-url/10996636'現在嘗試輸入相同問題的簡短URL'http://stackoverflow.com/questions/10992072',你會發現它被重定向到前一個URL。原因是它從數據庫中提取問題標題並將其附加到較短的URL中以使其對搜索引擎友好。 – anubhava

+0

在這種情況下,有問題的ID(10992072),但在pinterest的情況下沒有。 – xRobot