DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

TRUNG VU
TRUNG VU

Posted on

Setup An .Htaccess File For Redirecting To Laravel’s Public Folder

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>
Enter fullscreen mode Exit fullscreen mode

I hope it's helpful for you.

Top comments (4)

Collapse
mzpro10 profile image
Mazen El Zoor

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?

Collapse
cremirdevio profile image
Joseph • Edited on

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.

Collapse
saronlujan profile image
Saron Lujan

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.

Collapse
agusioma profile image
Terrence Aluda

Perfect

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.