I am new to Laravel and can’t seem to find the answer to a technical detail of the implementation. Essentially, when I put any given file inside the public
directory, for e.g. app.css
, and then navigate to localhost:8000/app.css
, the file gets served without me having to do anything.
This obviously leaves me wondering about how Laravel handles the request to localhost:8000/app.css
. To test things out, I tried adding a GET route inside web.php
as follows:
Route::get('/app.css', function() {
return 'Hello';
});
but when I navigate to localhost:8000/app.css
, it still returns the app.css
CSS file, not the ‘Hello’ text. This clearly means that Laravel first searches for a file inside the public
directory and if it can’t find one only then does it bring in the router.
My question is: Is this something that Laravel does or is it something that is done intrinsically by the built-in PHP server? In simpler words, is returning static files inside public
a concern of the server itself or of Laravel.
I tried inspecting the source code of Laravel but unfortunately I can’t trivially find any file where a check is made for a matching file in public
before serving it.
2
Answers
This is server related of course. Apache and Nginx are widely used web servers. Whichever you use, you can determine whether to redirect an incoming request to an index.php or a static file.
An example conf for Nginx might be:
This sample code makes index.php interpret all css files. Even though this is not the correct method, I added it to explain how it works.
I think the correct method should be what you encounter. In other words, if the file is physically located on the disk, it must be returned, otherwise index.php must interpret it. For this reason, if you want Laravel to open the file instead of index.php, you should delete that file.
If you are using
php artisan serve
, Laravel checks for the existence of files in public.https://github.com/laravel/framework/blob/11.x/src/Illuminate/Foundation/resources/server.php
This is a common behavior on web servers.