2015-01-04 63 views
3

我遇到一個很常見的問題,我需要改變我的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

目前還不清楚你想要什麼這樣做,但這裏有一些想法。 (1)爲此使用htaccess是很好的;它實際上比嘗試單獨在PHP中完成更好。 (2)你的'RewriteRule'沒有任何'title'參數,但這就是你在PHP腳本中尋找的東西。 – 2015-01-04 15:04:54

+0

@EdCottrell取決於。我通常更喜歡將所有請求重定向到'index.php',並且有一個完善的'Router'對象來處理我的路由。 – 2015-01-04 15:05:44

+0

@SecondRikudo我可能應該更清楚。我和你一樣,但你仍然需要以某種方式進行重定向,通常是htaccess。無論如何,它與隱形無關。 – 2015-01-04 15:08:01

回答

1

我需要改變我的site.com/page.php?id=1 &標題=頁面標題site.com內的不同的方法/頁標題-ID

您可以通過這一個替換當前的htaccess代碼(假設它位於文檔根目錄文件夾)

<IfModule mod_rewrite.c> 
    Options +FollowSymLinks -MultiViews 

    # Turn mod_rewrite on 
    RewriteEngine On 
    RewriteBase/

    RewriteCond %{THE_REQUEST} \s/page\.php\?id=([0-9]+)&title=([^\s&]+)\s [NC] 
    RewriteRule^%2-%1? [R=301,L] 

    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule ^([^/]+?)-([0-9]+)$ page.php?id=$2&title=$1 [L] 
</IfModule> 

此代碼將舊的URL格式(http://example.com/page.php?id=1&title=page-title)重定向到新的格式(http://example.com/page-title-1),然後將在內部重寫回新格式的舊格式(沒有任何無限循環)

+0

好吧我將我的.htaccess移到了我的index.php文件所在的位置,並且仍然不起作用,我會更詳細地介紹Apache配置文檔,並在您獲得正確工作後立即將您的問題標記爲正確。謝謝。 – octohedron 2015-01-04 15:43:04

+0

對不起,但是當我去site.com/page/default-2它不斷給404消息:\ – octohedron 2015-01-04 15:59:32

+0

你沒有提到'/ page /'子文件夾,所以這段代碼不能工作。請提供您需要的真實網址(舊格式和新格式) – 2015-01-04 16:02:39