Search code examples
php.htaccessroutesfastroute

PHP routing not working unless using an absolute path with index.php


With nikic/fast-route PHP package for url routing :

PHP url routing doesn't work unless I specify the whole path for the route instead of just the name of the route :

For example, in order to create a route for /hello-world, I have to specify the whole path : localhost/myProject/public/index.php/hello-world

$r->addRoute('GET', '/localhost/myProject/public/index.php/hello-world', function () {
        echo 'Hello World';
    });

Is there something that needs to be done in the .htaccess file ?

specifics about the current project :

I'm not using a framework but Patrick Louys' No Framework tutorial on GitHub : https://github.com/PatrickLouys/no-framework-tutorial

I'm using XAMPP on Fedora Linux as a web server

my code resides in my /home directory while the Web server is in /opt/lampp ... I've linked them with a symbolic link : sudo ln -s /home/... /opt/lampp/htdocs (if that matters)... I know that the tutorial rely on PHP built-in server (php -S localhost:8000)


Solution

  • My quick fix :

    1- Create a .htaccess file in the public directory. All requests will be forwarded to index.php

    2- Add a function to parse the whole URL submitted in order to retrieve the proper URI. Basically the function trims the whole url like localhost/public/index.php/hello-world and returns /hello-world. /hello-world being the route registered by our fast-route router, the appropriate controller will be called when such an url is received by our web server

    Source (explanations and code example) : http://blogs.shephertz.com/2014/05/21/how-to-implement-url-routing-in-php/