In this post, let's learn how to setup an .htaccess file for redirecting to Laravel’s public folder.
In Laravel the path for serving your web page is in the /public folder. By default after installing Laravel and navigating in a browser to the URL you will see a directory listing of all the Laravel files. Here’s an easy way using an .htaccess file to redirect requests of user to the Laravel /public folder mod_rewrite.
Create a .htaccess file in your root directory and add the following code.
<IfModule mod_rewrite.c>
# That was ONLY to protect you from 500 errors
# if your server did not have mod_rewrite enabled
RewriteEngine On
# RewriteBase /
# NOT needed unless you're using mod_alias to redirect
RewriteCond %{REQUEST_URI} !/public
RewriteRule ^(.*)$ public/$1 [L]
# Direct all requests to /public folder
</IfModule>
I hope it's helpful for you.
Top comments (6)
Is this safe? I thought the whole idea is to place all files outside the public_html directory so that none of the important files get accessed by accident?
It is absolutely safe. Placing the public folder in public_html and moving other files outside public_html is not the right approach, its a tweak. It won't be helpful if you deploy with SSH.
The actual way would be to place the whole files & folders in public_html, then configure your document root to point to the public folder in your laravel project.
But since you can't change the document root of your top-level domain in most shared hosting, hence, the need for using .htaccess file to perform the configuration.
PS: You can configure the document root of a sub domain even on a shared hosting, so you won't need this hack.
Hi! In your opinion, it is more advantageous to change the document_root or use htaccess. Is there a significant difference between the two? Because I can change the document_root, but lately I'm using .htacess because it's easier and faster and I can configure it in the deploy directly.
Not just an advantage. It is the right approach.
An excerpt from Laravel Doc:
laravel.com/docs/9.x/deployment#nginx
To the main question: there's no significant difference, .htaccess is a normal configuration for your webserver, so its fine to do it there too.
helped a lot
thanks__
Perfect