How to Rewrite URLs to index.php in Apache


rewrite urls to index.php

Sometimes, you might need to redirect all your URLs to index.php which then decides what to do with each request. You can easily do it using .htaccess in Apache. Let us look at how to rewrite URLs to index.php in Apache.

 

How to Rewrite URLs to index.php in Apache

Here are the steps to rewrite URLs to index.php in Apache

Before you proceed, please ensure you have enabled .htaccess (mod_rewrite) in Apache. If you haven’t, then here are the steps to do it

 

Open the .htaccess file using a text editor. You will usually find it at your website’s root document folder (/var/www/html/). If you don’t find it, just create a blank file with name .htaccess. Remember to put a dot (.) at its beginning so it remains hidden.

 


$ sudo vim /var/www/html/.htaccess

 

If you have placed your site documents in a subfolder, place the .htaccess file in that subfolder.

 

Add the following rules to .htaccess file


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

 

In the above code,

The first line enabled URL rewrite engine for Apache


RewriteEngine on

 

The following lines check for existing files (-f) and folders (-d)


RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

 

The following line performs the actual redirection


RewriteRule . index.php [L]

 

 

If you also want to pass the requested path to index.php as one parameter, you can modify the RewriteRule as


RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

 

In this case, the URL part after your domain will be passed to index.php

So http://example.com/product will be redirected to http://example.com/index.php?q=product

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!