如何用PHP创建SEO友好搜索?

时间:2013-08-31 13:05:56

标签: php .htaccess

这是我在我的网站中使用的搜索脚本。此搜索文件作为search.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或其他方法做到这一点?

3 个答案:

答案 0 :(得分:1)

通过httpd.conf启用mod_rewrite和.htaccess,然后将此代码放在.htaccess目录下的DOCUMENT_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]

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您可以将.htaccess与重写规则一起使用,例如

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