Skip to content

Latest commit

 

History

History
63 lines (43 loc) · 1.82 KB

05.1-rewrite-engine.md

File metadata and controls

63 lines (43 loc) · 1.82 KB

Redirecting to index.php

With Apache's .htaccess

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:

  1. A regex expression where urls will be matched against
  2. The php file where Apache will redirect the route into
  3. 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 [ ].

For more information aboute rewrite rule flags, see this documentation.

Preventing Redirects to index.php Rewrite Conditions (RewriteCond)

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