Installing Laravel In Sub Directory & Deny Access To It


Read {count} times since 2020

Laravel is a PHP framework that reduces the work load of creating PHP applications. As it is a framework, there are limitations and some problems just like any other PHP program.

Laravel framework has a “public” folder. The HTML files that are going to be displayed on Web Server will be from this folder. Since it is a sub directory of the framework, to access the real site, we would have to go to the following URL :

http://example.com/public

Actually, with some server configuration you can change the Document Root to the “public” folder, but only  some hosting providers provide this. Also, in cases that you’re running an Open Source application, you can’t just update the repo / open source code with a single click. This is one of the big problem of the Laravel framework.

I didn’t like this and decided to cope up with a way to make the site under  a single tree instead of separate branches. I first thought of routing the requests from the root to the public folder, but it won’t deny the access of the other folders of the framework.

So, I made a sub folder inside the document root and put all the files of the Laravel framework inside that sub directory. The with some htaccess code on the root, everything was working with 403 access denied to the Laravel installation sub directory.

Move / Create Laravel Installation

Create a sub directory on your site root. For this tutorial we use “laravel”. If your site root already have Laravel files, move it to the new sub directory. Other wise create the Laravel installation in the sub directory we created. Any changes to Laravel code must be done in this sub directory.

At The Root

Now we make a .htaccess file (Apache Web Server) in the site root with the following content :

<IfModule mod_rewrite.c>
  Options -MultiViews
  RewriteEngine On
  RewriteBase /laravel
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*?)$ public/$1 [L]
</IfModule>

What the above code do is, redirect all requests from the site root to the “public” folder of the Laravel sub directory. In this case it’s “laravel”.

At The Sub Directory

We make another .htaccess file in the “laravel” sub directory with the following code :

RewriteEngine on 
RewriteRule $ - [F]

The above rules will show 403 Access Denied error when a native browser or external client access the “laravel” web URL directly. But won’t show the error when some script on the site itself access this folder. In our case it’s the .htaccess at root.