phplaravelapachecakephp-routing

How can I force all URI requests to index.php?


In my index.php (which is in my project root directory) I have a basic routing system that grabs the url (using $_SERVER[‘REQUEST_URI]) and calls the proper ‘controller’ which then calls the proper ‘view’ (so, implementation of very basic MVC). What I have in my index.php looks like this:

$router= Router::load('Routes.php');
$uri=trim($_SERVER['REQUEST_URI'],'/'); 
require $router->direct($uri);

Problem is, I can not seem to make all requests go to index.php. Obviously if you go to localhost/myproject/ you will get to index.php (therefore the proper controller will be called), however what I want is that even if you type localhost/myproject/contact to first be direct to index.php. So that index.php can handle routing for you.


Solution

  • If you are using apache you can use .htaccess file to redirect every request in your index.php file:

    RewriteEngine On
    
    RewriteRule ^/index\.php$ - [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
    

    If you are using nginx server you can redirect all request to index.php file with this code in your .conf file:

    location / {
        try_files $uri $uri/ /index.php;
    }
    

    Hope this helps you