Clean URLs for search query?

落花浮王杯 提交于 2019-11-27 02:06:42

I think the problem is that you've created an HTML form with GET method, which automatically opens the URL that way you specified as the result. If you want to submit your search query like the desired one, you should hack the form with some JavaScript to call your good-looking URL like this:

<form method="get" action="/search/" onsubmit="return false;">
<input type="search" name="q" value="querystring" />
<input type="submit" onclick="window.location.href=this.form.action + this.form.q.value;" />
</form>

I think you'll actually have to create a separate rewrite rule that is essentially your rewrite rule above but in reverse. Then place it above your first rewrite rule.

RewriteRule ^/search?q=([-0-9a-z]+)$ /search/$1 [NC]
RewriteRule ^search/([-0-9a-z]+)$ /search.php?q=$1 [L]

Seem pretty ghetto to me though. Maybe you should remove the submit button from your form and redirect using javascript.

See the trick on this this page. The trick is to send the form to self (or I guess you could redirect to an intermediate page), and use server side logic to redirect using a clean URL.

DADU

For everybody trying to solve this problem only with mod_rewrite (without JavaScript), see this question: Redirect and rewrite with mod_rewrite

EXAMPLE WITHOUT JAVASCRIPT

Have your search form action set to 'searchredirect.php' instead and input name to 'q'.

Create a new php file called searchredirect.php and have only the following code:

<?php  
if (isset($_GET['q'])){  
$url = $_GET['q'];  
header("location: search/".$url);  
} else {  
header("location: search");
} 
?>

Name you original search page 'searchclean.php'

In your .htaccess file have the following rewrite rule:

RewriteRule ^search/([^/]*)$ /searchclean.php?q=$1 [L]
Steini Petur

I just kept

RewriteRule ^search/([^/\.]+)/?$ search.php?q=$1 [L]

in my .htaccess, i made search_redirect.php with the code given here below:

<?php  
if (isset($_GET['q'])){  
$url = $_GET['q'];  
header("location: search/".$url);  
} else {  
header("location: search");
} 
?>

Then of course I redirected my forms to goto search_redirect.php and voila. This combination worked like a charm, then since I have pagination I didn't have to do anything more, since all of them use GET on the query string and then $i for the integer.

RewriteRule ^search/([^/\.]+)/page/([^/\.]+)?$ search.php?q=$1&pn=$2 [L]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!