Suppose we have the following requests that we want to handle:
https://www.jollibeedelivery.com.ph/products https://www.jollibeedelivery.com.ph/cart
First, let's try rewriting
/products to be handled by index.php
.
In our .htaccess
file, we'll write something like:
RewriteEngine On
RewriteRule ^products index.php [L]
This means that when the route /products
is accessed, redirect the request to index.php
.
To redirect with all routes:
RewriteEngine On
RewriteRule ^(.*)$ index.php [L]
The RewriteRule
accepts 3 parameters:
- A regex expression where urls will be matched against
- The php file where Apache will redirect the route into
- Is the flag for the rewrite.
- In this case, we used
[L]
.[L]
(Last) is a flag that means that if this rule matches, then no other rule matching will be performed for this page. - You can add multiple flags inside the
[ ]
.
- In this case, we used
For more information aboute rewrite rule flags, see this documentation.
With the current setup, even routes to our assets will be redirected to index.php
. Since we don't want that, we specify:
RewriteCond %{REQUEST_FILENAME} !-f
Which tells us to not process this RewriteRule if the resource being accessed is a file -f
.
But what if our assets is inside a folder? For this, we'll have to rewrite condtions for folders (directory) as well
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
There are also chances that our folders/directories are in symbolic links. For this cases we add -l
:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l