2013-08-31 205 views
-1

這是我在我的網站中使用的搜索腳本。該搜索文件保存在主目錄的search.php如何使用php創建搜索引擎友好搜索?

<?php 


    $searchTerm = trim($_GET['q']); 
    $searchlink = str_replace(" ","_",$searchTerm); 
    $id = trim($_GET['q']); 
    if($searchTerm == "") 
    { 
     echo "Enter name you are searching for."; 
     exit(); 
    } 

    $host = "localhost"; //server 
    $db = "db"; //database name 
    $user = "user"; //dabases user name 
    $pwd = "ss1122"; //password 
    $link = mysqli_connect($host, $user, $pwd, $db); 
    $query = "SELECT * FROM mytable As a JOIN mytable2 As b ON a.mycolumn=b.mycolumn WHERE a.mycolumn LIKE '%$searchlink%'"; 
    $results = mysqli_query($link, $query); 
    print "<div class=\"box-title\" style=\"border-bottom:1px solid #efefef; padding-bottom:10px; margin-bottom:5px;\">You Searched for \"$searchTerm\"</div>"; 
    print "<div class=container><div class=container-top><div class=container-bottom>"; 
    if(mysqli_num_rows($results) >= 1) 
    { 
     $output = ""; 
     while($row = mysqli_fetch_array($results)) 
     { 
     $output .= "<h4><a href="$row['mycolum'] . "/>Search result</a></h4>"; 

     } 
     echo $output; 
    } 
    else 
     echo "There was no matching record for the name " . $searchlink; 

    ?> 

當過用戶搜索的東西說「免費」的鏈接變得http://mysite.com/search.php?q=free

雖然我想這個搜索鏈接成爲http://mysite.com/search?q=free

如何我們可以用.htaccess或其他方法做到這一點嗎?

+0

可能的複製:http://stackoverflow.com/questions/3615097/php-seo-friendly-urls?rq=1 – Sumurai8

+0

另一種可能的重複:h ttp://stackoverflow.com/questions/14323920/htaccess-remove-php-extension – Sumurai8

回答

1

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

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

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(search)\.php(\?q=[^&\s]+) [NC] 
RewriteRule^/%1%2 [R=301,L] 

RewriteRule ^(search)/?$ /search.php [L,QSA,NC] 
+0

工作得很好。但有一個問題,鏈接包含重複關鍵字,即搜索?q = free&q = free –

+0

確定從第一條規則中刪除'QSA'標記或檢查編輯。 – anubhava

+0

根據需要工作得很好。幹得好anubhava –

0

您可以使用.htaccess與重寫規則如

RewriteEngine on 
RewriteBase/
RewriteRule ^search?q=(.*)$ search.php?q=$1 [QSA,L] 
+1

這不起作用,因爲RewriteRule的不包括查詢字符串!查詢字符串需要與單獨的'RewriteCond%{QUERY_STRING}'匹配。 – Sumurai8

+0

@ Sumurai8。正確地說,它不起作用。 –

1
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L, QSA] 
+0

這也有效。 –