我遇到一個很常見的問題,我需要改變我的site.com/page.php?id=1 &標題=頁面標題爲site.com/page-title-id將PHP的GET變量轉換爲友好的URL?
我認爲這可以很容易地在.htaccess文件中添加一些mod_rewrite,但我覺得它可能不是最友好的搜索引擎優化方法,你覺得怎麼樣?
另一種方法是在PHP代碼中進行一些更改,但是我對這種語言比較陌生,並且我不知道PHP提供的所有庫和函數,並且可以使我的生活更輕鬆。
到目前爲止,我在做什麼(這是不工作)在我的.htaccess:
# BEGIN ocasion_system
<IfModule mod_rewrite.c>
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase/
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php\?title=([^&\s]+)&?
RewriteRule (.*)\.php$ /$1/%1/? [L,R=301]
RewriteRule ^([^/]+)/([^/]+)/$ $1.php?title=$2 [QSA,L]
</IfModule>
而且我page.php文件具有
//all includes up here..
$page = new Page();
$page->__set('title', $_GET["title"]); //this is how i set up my page interface, please don't laugh
if ($_GET["title"] != NULL){
$page = get_page($page, $db);
echo '<pre>';
print_r($page);//works as intended when i access http://localhost/page.php?title=default prints all the Page object with that title.
echo '</pre>';
}
我想在PHP中的解決辦法要好得多,因爲我不想讓搜索引擎認爲我在掩蓋網站或重定向或任何其他內容,只是希望網址類似於site.com/page-title-id或類似網址。
編輯:試過的.htaccess
目前還不清楚你想要什麼這樣做,但這裏有一些想法。 (1)爲此使用htaccess是很好的;它實際上比嘗試單獨在PHP中完成更好。 (2)你的'RewriteRule'沒有任何'title'參數,但這就是你在PHP腳本中尋找的東西。 – 2015-01-04 15:04:54
@EdCottrell取決於。我通常更喜歡將所有請求重定向到'index.php',並且有一個完善的'Router'對象來處理我的路由。 – 2015-01-04 15:05:44
@SecondRikudo我可能應該更清楚。我和你一樣,但你仍然需要以某種方式進行重定向,通常是htaccess。無論如何,它與隱形無關。 – 2015-01-04 15:08:01