Tag Archives: rewirterule

Sending information through GET Method (URL) using RewriteRules instead of QueryStrings

Small Pretty URLs tutorial.

Imagine the your app have a search form that allows the user choose a  book category, the author and/or the publisher.

The generated URL in get method for an query example would be something like:

http://localhost/search.php?category=12&author=22&publisher=12
or if we choose only the publisher field:
http://localhost/search.php?publisher=12

We can use Apache Rewrite Rules to transform it into a search engine robot readable link. The URL would be something like this:
http://localhost/search/category/12/author/22/publisher/12

.htaccess file needs these directives:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php
RewriteRule ^search search.php
RewriteRule ^(.+)category/([0-9]+)/? search.php/?category=$2 [QSA]
RewriteRule ^(.+)author/([0-9]+)/? search.php/?author=$2 [QSA]
RewriteRule ^(.+)publisher/([0-9]+)/? search.php/?publisher=$2 [QSA]
</IfModule>

[QSA] (Query String Append) is a flag that makes Apache concatenate the Query Strings generated by all rules defined on .htaccess. This make all following queries work, independent of the variables order:

http://localhost/search/category/12/author/22/publisher/12
http://localhost/search/publisher/12/author/22/category/12

Regular Expressions

I’m not expert on Regular Expressions, but I’ll try to explain those I used in the given examples

^(.+)category/([0-9]+)/?

^ indicates the string start, the browser URL in this case or everything after the first slash from host name on and everything before the query string (the interrogation sign). On our example, this is the string:
/pesquisa/categoria/12/autor/22/editora/12

“.+” indicates that one or mor chars can be found from the string’s start and the word “category/”. Both chars are inside a parentheses because we want to indicate that the found result should be assigned to a var, in this case, the var will be $1.

The expression is [0-9] indicates that we search for numbers only. The “+” sign after [0-9] indicates that we look for one ore more numbers, and the parentheses indicates that we want to assign the found result into a next var ($2).

Finally, the expression “/?” in the end of the string, indicates that a slash can be found or not in the end of the string.