Laravel deny access to /public directory

Viewed 804

Someone can answer me: Is it possible in laravel to deny access to the directory inside the public folder? I understand that everything in the public directory is public. But I need to place an folder in the /public directory and file index.html in it with some css, js, images. I need to display correctly index.html and prevent unauthorized users from viewing it. I would be very grateful for any answer.

2 Answers

The problem is, static files inside /public are NOT handled by laravel, but they are served directly by your server software.

If you are using apache2, you can deny access to a public subfolder you could place an .htaccess file inside the directory denying access:

public/custom/.htaccess

order deny,allow
deny from all

The problem is, you would have no way to authorize access to those files outside unless you use basic auth, which is extremely basic.


In order to handle complex authorization and not disrupt laravel conventions, I would place those files inside a folder inside resources (or even storage/app)

resources
 |  custom
 |   | index.html
 |   | image.png
 |   | script.js
 |   | style.css

Then, in your web.php create a generic route for everything inside your original folder:

Route::get('/custom/{file?}', [CustomFilesController::class, 'getFile'])

Inside the controller/route you can:

  • perform your authorization
  • retrieve the files from the resources (or storage) folder
  • serve them in response with the appropriate content type header

Try setting permissions on that specific folder as per your requirement.

Simply set:

chmod -R permission folder_path/folder_name

You can see this link to know what combination is used for which permissions. chmodcommand.com

Related