I am routing all the http requests to a website to the index.php file and then handling it from there in MVC fashion. But, if the request is made /api
route, then another file Api.php should handle it. How do I make that happen?
^ this is what I tried, but it just gave me a 500 error
Also, any insight into best practice concerning this is appreciated. I'm trying to write a PHP MVC framework, so I'd also like to know if this is the right way to go about with routing
Top comments (9)
Just a side note. The best way is not to use .htaccess. (Ignore me if you did know it already) :D
Considering the beginner question I would say using a .htaccess file is a good thing for now. Easier to test and experiment with.
I also tell beginners they can use .htaccess but I also say that they (apache2 documentation) don't recommend it. It's something good to know even if you are a beginner :)
I have to set it up on a shared hosting, so access to httpd.conf isn't available :) but thanks a lot!! Like I said, I am also trying to write a PHP MVC framework, so every bit of info is useful
First read the open source code of the most popular PHP MVC frameworks, see how they handled these problems. Most likely you will make the same mistakes like they did 15 years ago, learn from them, it will be quicker.
does changing
^api
toapi/(.+)$
fix it?To get more info on the 500 error, check Apache's error logs. Usually they're stored in
/var/log/apache2/error.log
. You can use the following command to print the last 30 lines of that file:I'm going to guess that the Rewrite module isn't enabled. If that's the case, enable it and restart Apache:
Personally, I'd use a PHP HTTP router instead. Link all requests to something like
index.php?uri=$1
. That's how most frameworks do it. A lot less rewriting. And then they just pass$_GET['uri']
around.And if the URI is
/api/users/1
get the user by the ID of 1. Pretty simple.I would say both Meghan and Kamal are right :)
As a side note, I usually like debugging my htaccess calls using htaccess.madewithlove.be/ since it explains what it matches based on an url. It's definitely not perfect, but it helped me debug some more complex rewrite rules.
PS:
In the future for easier debugging it would help a lot if you would copy/paste your code as text, not as an image.