DEV Community


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

Enter fullscreen mode Exit fullscreen mode

I hope it's helpful for you.

Top comments (6)

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?

cremirdevio profile image
Joseph • Edited

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.

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.

Thread Thread
cremirdevio profile image
Joseph • Edited

Not just an advantage. It is the right approach.

An excerpt from Laravel Doc:

Please ensure, like the configuration below, your web server directs all requests to your application's public/index.php file. You should never attempt to move the index.php file to your project's root, as serving the application from the project root will expose many sensitive configuration files to the public Internet

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.

mostafabinesh profile image

helped a lot

agusioma profile image
Terrence Aluda