October 1, 2012

PHP .htacces and index.php redirection

Question by Emann Tumala Saligue

I am new about this redirection and I want to know how it works?
I have some file called index.php and i want to hadlle it any directory in the site



The url is:

test 1. www.example.com/ - will view the include home.
test 2. www.example.com/settings - will view the include  settings.
test 3. www.example.com/errorsample - will view the include   404 page.

How to make .htaccess and index.php using that code or any idea how it works and sample code of it.

Answer by Starx

I will try to explain this with a simple example. Consider the following .htaccess file

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ /index.php?x=$1 [L] 
#  ^ This is the rule that does the redirection

What it does is, it routes every url request and sends the request to index.php. How it send it? I will show couple of example to do that.

  • www.example.com/settings will be send as www.example.com/index.php?x=settings
  • www.example.com/errorsample will be send as www.example.com/index.php?x=errorsample

So, now you are configure your index.php and decided what you want to do, with the value you get in $_GET['x']

switch($_GET['x']) {
   case "profile": include("include/profile.php"); break;
   // .... similarly other cases
   default: include("includes/home.php"); break;


Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!