Diga
Diga

Reputation: 491

PHP Redirect Form to Custom URL

I've an .htaccess code for redirecing search result page.

RewriteRule ^search/([a-zA-Z0-9\-]+)$ search.php?query=$1 [L,NC]

So when you go /search/blabla you simply go to search.php?query=blabla

It works, no problem. When I write address bar /search/blabla it shows results.

The problem is, when I use my search form, it sends me to search.php?query=blabla (no suprise)

Here is my form code:

<form id="search" name="search" action="search.php" method="get">
    <table>
        <tr>
            <td><input type="text" size="20" maxlength="100" name="query" id="query"></td>
            <td><input type="submit" value="Search"></td>
        </tr>
    </table>
</form>

I want this form to redirect me to search/query not search.php?query=query

How can I do this?

Upvotes: 1

Views: 265

Answers (2)

php_nub_qq
php_nub_qq

Reputation: 16065

I've had the same problem and what I ended up doing is using JavaScript to intercept the submit.

form.onsubmit = function(){
    var url = 'http://example.com/search/query';
    // obviously you will have some logic generating the url

    window.location = url;
    return false;
}

A little explanation.

I don't think rewrite rules are needed since this is very basic functionality in javascript and is supported in all browsers. The fact that you might be missing is that rewrite rules are performed on every single request meaning that if you have more rules, which you probably do, it will have to run all the regular expressions on all requests. This is rather pointless because, depending on your application, most of the rules will count for a very small amount of the requests, which means that you are wasting processing power in the long run and regular expressions are something that you should avoid using unless there is no alternative. I know the waste may be small but when you end up doing many micro optimizations like this one it may turn out significant in the end.

Just saying.

Upvotes: 1

anubhava
anubhava

Reputation: 786349

Insert this redirect rule before your earlier rule:

RewriteCond %{THE_REQUEST} \s/+search\.php\?query=([^\s&]+) [NC]
RewriteRule ^ /search/%1? [R=302,L,NE]

Upvotes: 1

Related Questions