RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
RewriteRule ^(.*)$ index.php [L]
In this post, we'll thoroughly examine the above code and see exactly how each section works. If the Laravel project has pages that produce errors, this guide can be helpful. It's sufficient that this code is placed in the .htaccess
file of your project. 📁
What's the main purpose of the code? 🎮
This code helps us ensure that every request made to the original server reaches the public
folder, and if nothing is found in the public
folder, it directs to index.php
. This ensures users always see the correct page, and if nothing is found, a 404 error is thrown.
Explanation of each line of code 📜
Line one: <IfModule mod_rewrite.c>
🔵 Explanation: This line checks whether the mod_rewrite
module is enabled on the server or not. Since this module is responsible for rewriting (Redirecting) URLs, without it, the rest of the code won’t work.
Line two: RewriteEngine On
🔵 Explanation: This line activates the rewriting functionality. It tells the server that the addresses currently configured should be changed.
Line three: RewriteRule ^(.*)$ public/$1 [L]
🔵 Explanation: Here we inform the server that every address it receives (meaning anything that comes after example.com/
) should be directed to the public
folder, but without changing anything in the address itself.
^
means the start of the address is being checked.(.*)
means anything that comes after that point.$1
refers to the same previous address.
So with this action, you maintain access to everything in the public
folder.
Line four: RewriteRule ^(.*)$ index.php [L]
🔵 Explanation: Now if nothing is found in the public
folder, this line will direct the address to index.php
. index.php
is the main Laravel file that processes requests and displays Laravel's 404 error to the user.