Tizag.com Webmaster Tutorials - A collection of webmaster tutorials from HTML to PHP.

Saturday, September 26, 2009

Steps for URL re-write

Step 1: you have to create a .htaccess file.

Step 2: Edit the htaccess file. In order for apache to be able to rewrite urls you have to switch on the so called Rewrite Engine. This is done by inserting RewriteEngine on into the htaccess file.

Step 3: Creating Rewrite Rules. You can create as many rules as you wish. assuming you have a page called http://www.mywebsite.com/myprofile.php and you want to be able to call it via http://www.mywebsite.com/myprofile you would have to insert the following line


RewriteRule ^myprofile $ myprofile.php

You will still be able to call the page http://www.mywebsite.com/myprofile.php. Once you have tested to see if rewrite works you can change all the links in your web pages from myprofile.php to myprofile.

Now lets assume you have a blog and you have a page where you display articles from a specific category and your url looks like http://www.mywebsite.com/category.php?id=81. You could rewrite it to http://www.mywebsite.com/category/81. Now you don't want to have to do this for all categories because if you add a new category you would have to write a new line.
RewriteRule ^category/([0-9]+)$ category.php?id=$1

What if you have multiple pages of articles within categories?

http://www.mywebsite.com/category.php?id=81&page=19
RewriteRule ^category/([0-9]+)/([0-9]+)$ category.php?id=$1&page=$2

If you are upgrading your website and you want to ensure that all the old links will still be working you can use the mod_rewrite module as well. All you need to do is simply creating a rule and indicate that the page has permanently moved.

Example:
RewriteRule ^oldpage.html$ newpage.html [R=301]
Conditions

You can also create a set of conditions. In the example below it is assumed that the subdomain beta is pointed to the same place as the main website.

The first line is the condition and checks what the host or domain name is. The second line will only be run if the first line it valid.
RewriteCond %{HTTP_HOST} ^www.domain.com$
RewriteRule ^category/([0-9]+)$ category.php?id=$1
RewriteCond %{HTTP_HOST} ^beta.domain.com$
RewriteRule ^category/([0-9]+)$ beta_category.php?id=$1

Other variables that can be used in the condition are

HTTP_REFERER

REQUEST_URI

REQUEST_FILENAME

REMOTE_HOST

REQUEST_METHOD

HTTP_USER_AGENT

If is also possible to combine multiple conditions
RewriteCond %{HTTP_HOST} ^www.domain.com$ [OR]
RewriteCond %{HTTP_HOST} ^beta.domain.com$
RewriteRule ^category/([0-9]+)$ category.php?id=$1

The above rule would only be exectuted if the domain is either www.domain.com or beta.domain.com. If the condition is not met the rule will be ignored.

No comments: