搜索页面包含友好的URL

时间:2011-10-04 15:41:37

标签: php .htaccess search mod-rewrite

我的网站上有一个搜索表单

<form class="clearfix" action="search.php" method="get">
                <h1>Search the Site</h1>
                <input class="field" type="text" name="q" id="query" value="" size="23" />
                <input type="submit" value="Search" class="bt_login" />
</form>

现在它发布到search.php,但我希望它发布到/ search / query-here。我的.htaccess文件现在看起来像这样

ErrorDocument 404 /index.php?p=404

Options +FollowSymLinks
RewriteEngine On 

RewriteRule ^(products|blog|feed|search|checkout|checkout)$ $1.php [nc]
RewriteRule products/cat/(.*)$ products.php?type=cat&cat=$1 [nc]
RewriteRule products/(.*)$ products.php?type=single&product=$1 [nc]
RewriteRule blog/(.*) blog.php&post=$1 [nc]
RewriteRule feed/(.*) feed.phptype=$1 [nc]

RewriteRule search\.php?q=(.*)$ /search/$1 [R=301,L]
RewriteRule search/(.*)$ search.php?q=$1 [NC]

RewriteCond %{HTTP_REFERER} !^$  
RewriteCond %{HTTP_REFERER} !^http://(www\.)?wghandcrafted.com/.*$ [NC]  
RewriteRule \.(gif|jpg|jpeg|psd|js|swf|flv|png)$ /feed/ [R=302]  

RewriteCond %{REQUEST_FILENAME} !-f  
RewriteRule ^images/.*\.jpg$ /images/default.jpg [L]

我该如何做到这一点?

2 个答案:

答案 0 :(得分:2)

我认为这样做的方法可能是

  1. 检测表单已提交
  2. 使用header()函数将用户重定向到正确的URL。
  3. 让.htaccess文件在后台重写URL
  4. 如果给出了正确的变量名称,则处理表单
  5. 这可能是无缝的,用户不会知道它已经发生。

    因此...

    使用method =“POST”和name =“search_form”修改表单

    <form class="clearfix" action="search.php" method="POST" name="search_form">
                    <h1>Search the Site</h1>
                    <input class="field" type="text" name="q" id="query" value="" size="23" />
                    <input type="submit" value="Search" class="bt_login" />
    </form>
    

    <强>的.htaccess http://website.com/search/search+term的形式获取网址,并在后台重写为http://website.com/search.php?q=search+term

    RewriteRule ^search/(.*)$ /search.php?q=$1 [R=301,L]
    

    <强> PHP

    if ($_POST['search_form'])
    {
    
        // Get the search query
        $search_query = $_POST['q'];
    
        header("Location: search/" . urlencode($search_query));
        exit();
    }
    else if ($_GET['q'])
    {
        $query_from_url = $_GET['q'];
    
        echo "The query from the URL is" . $query_from_url;
    }
    

答案 1 :(得分:0)

我认为你可以删除或注释掉这一行:

RewriteRule search\.php?q=(.*)$ /search/$1 [R=301,L]

然后获取表单提交给自己,在search.php页面上获取变量并构建所需的字符串然后使用:

header("location:search/nice+string")