<? Online-PHP::Tutorials ?>
-
Created: 11 May 11
URL Rewrite - Simple configuration
Hello All,
First of all, What you are going to do, how, and how will you use it - simple steps:
1. Configure your application so that all the URLs will lead to one script file - index.php
2. The main file index.php parses the REQUEST_URI (i.e. the URL) to determine the request
3. Load scripts and files relevant to the request.
1. Redirect all traffic to index.php
create file named ".hraccess" in your root folder, and put the next content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php
This script tells the server to redirect all the traffic except files to the main index.php file
2. In the main index.php file, use the next script to determine URL parameters and query string request:
$url_arr = parse_url($_SERVER['REQUEST_URI']);
$url_path_arr = explode('/', trim($url_arr['path'], '/'));
$controller = $url_path_arr[0];
The lines create two important variables:
$url_path_arr - Array which contains required "folders" as array items. It means that if the URL looks like "example.com/get/path/in/site/", the array will look like:
array([0]=>'get', [1]=>'path', [2]=>'in', [3]=>'site');
Now, you know what is the request, i.e. what the user wants to receive from the server, and you can load the relevant scripts and files.
3. array elements
As a suggestion, use the first array element as a "controller", i.e. the first element is the name of the script (PHP) file, which is located in "Controllers" directory. In this way, the above example will lead to the next PHP file:
/Controllers
....get.php
Now if you create another file in this directory, let's say "about.php", you will reach this file through "example.com/about/" URL.
All the other elements can be used as URL Paramerers. I.e the URL "example.com/about/application/" will lead to Controllers/about.php file and the "application" is the parameter to the file.
Important!!!
*Using this method of URL Rewrite will require ALL PATHs to files (css, js, ...) to be ABSOLUTE, i.e. starting with "/"
"example.com/styles/style.css"
"example.com/scripts/script.js"
Enjoy