Twinkle
Basics of How Routing Works
The usual "the very thing you're trying to do is wrong" question.
https://teratail.com/questions/jyl7cyfq0dcnkv
There are many questions about wanting to display http://localhost/test.php
without the .php
extension as http://localhost/test
. However, the initial idea that "simply omitting the .php
should work" is incorrect.
Since the initial idea is wrong, no matter how much you search, you will only arrive at incorrect answers.
In frameworks like Laravel, .php
is not visible, but it's not because it is omitted.
Simple Flow Explanation
- All requests are routed to
http://localhost/index.php
. - Inside
index.php
, the nature of the incoming request is examined. If it’shttp://localhost/test
, it is determined that a request to/test
has been made. - The request is dispatched based on the request information.
Laravel’s routing writes this dispatching method.
Route::get('test', TestController::class);
Implementation Methods
- Routing everything to
index.php
is the job of the web server.
For nginx:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
For Apache, using .htaccess
:
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
- Inspecting the request is the job of the framework, so you don’t need to know the details.
- Dispatching is also the job of the framework.
In the end, what the user needs to do is just configure the web server and write routing.
Even if you don’t know the details, you can use the framework.
As long as you route everything to index.php
, the framework will handle the rest smoothly.
Explanation that .php
is not being omitted ends here.
Before the Era of Frameworks
Around the 2000s, people would write code to inspect requests themselves.
For a request to http://localhost/index.php/test
, /test
would be extracted and dispatched.
Request details could be obtained with the $_SERVER
variable, using $_SERVER['PATH_INFO']
or $_SERVER['REQUEST_URI']
.
From the stage of http://localhost/index.php/test
, if you also configure the web server to route everything to index.php
, /index.php
will disappear, leading to modern routing.
While frameworks may be doing more complicated things, the basic mechanism is the same.