Using Htaccess in PHP Engine
In order to create a website engine, first you need to make sure that any URL request of the site is processed by one PHP file.
This is done using a special file
.htaccess. Let's create this file
and enable it by writing the following
lines at the beginning of its text:
RewriteEngine On
RewriteBase /
After that, we can specify which file
should process the requested URL. This
is done using the RewriteRule command.
Let's look at the work of this command in practice.
For example, let's make the address /test
be processed by the file index.php:
RewriteRule /test index.php
The first parameter of the RewriteRule command
actually takes a regular expression.
Let's use it to make all URLs
be processed by the file index.php:
RewriteRule .+ index.php
However, some addresses still should not be redirected. These are addresses that lead to resource files: CSS, JavaScript, images, and so on.
Let's cancel their redirection using the
RewriteCond command:
RewriteCond %{REQUEST_URI} !\.(js|css|ico|jpg|png)$
RewriteRule .+ index.php
On the index.php page, we can get
the requested URL using the superglobal
array $_SERVER:
<?php
$url = $_SERVER['REQUEST_URI'];
?>
Create a .htaccess file. Use it
to implement the redirection of all requests
to index.php.
Display the requested URL on index.php.