Friday, April 2, 2010

htaccess : URL Rewriting

URL rewriting takes the url submitted by the browser and adjusts it to be interpretted by the web server in a different way. In othewords, rewriting allows you to send people to yourdomain.com/a/1/b/2/c/3 and the server will serve up the page for yourdomain.com/index.php?a=1&b=2$c=3. What this does is allow you to take dynamic urls and rewrite them to look and act like static urls. The benefit to this is that it enables some search engines to index your page using parameters they would not previously have been able to.

URL rewriting can be helpful in a few ways. The most common URL rewriting is done on Apache servers. To set up URL rewriting on an Apache server, you need to be able to access the .htaccess file. In the directory where you want to perform URL rewriting, you need to open the .htaccess file. If it does not have one, create a new one. If you do not know how to do this, click on the .htaccess "home" link to the left.

URL rewriting at its best uses regular expression. HowGuru.com addresses regular expression elsewhere on the site, but a brief statement will suffice here. Here is the structure of a rewrite statement:


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ page.php?variable_1=$1 [QSA,L]


The "" tells the server to look for the rewrite module, if the server can rewrite urls, then follow the code until "." Othewise, if the server does not have a rewrite module, it will ignore the information between the "if" brackets.

The next line ("RewriteEngine on") activates this function on the server.

The next line ("RewriteCond %{REQUEST_FILENAME} –d")states a condition for the rule to apply. In this case, a file name is being requested.

Finally comes the rule with is proceeded by "RewriteRule". This is followed by the regular expression statement defining what pattern to look for, which is followed by the destination file and/or query string combination to search for on the server.

The regular expression is pretty easy to understand. Regular expression is all about finding patterns, the “^” indicates the beginning of the input. The “$” at the end indicates the end of the input. Numbered variables are assigned to each pattern that meets the criteria in each set of parenthesis. So if I wrote:

RewriteRule ^(.*)$ page.php?var_1=$1 [QSA,L]

The “(.*)” refers to any set of numbers and letters and length long, this is then referred to in the destination page portion of the rule as “$1”.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home