Laravel: How to protect .env files?

Laravel: How to protect .env files?

.env files:
If you develop your applications using Laravel, you probably use .env files every day in your development life. We use these files to store the most secret information of our application. Be it database credentials, the application key or any third-party service credentials.

So simply put: We do not want anyone to get access to these files!

But the truth is: quite a few .env files are accessible. And I don’t mean that they are accessible by some hackers, but by Google.

To search for public .env files, all you need to do is google for one of these terms:

DB_USERNAME filetype:env
DB_PASSWORD filetype:env
APP_DEBUG filetype:env

Secure your .env files
The reason that these .env files are accessible and also get scraped is because of two things:

Misconfigured shared hosting
The .env file has the wrong access rights
Shared hosting
If you use shared hosting, please make sure that the root folder of your Laravel application is not accessible from the outside.

Only “public” folder should be accessible from the webserver. If you cannot modify these settings on a shared hosting system, move to a VPS now.

Wrong .env access rights
Another possible issue could be, that your .env file simply has the wrong access rights.

Set the CHMOD of your .env file to 400 or 440 so that it cannot be accessed by public users.

These should all be quite obvious things, that you usually do not have to deal with — but since it comes up on Google, I thought it will be worth talking about this.