How to protect your .env file from public access in Laravel?

2024-04-27 07:18:09 Deepa tcs Laravel

How to secure .env file in laravel

If you are a developer and developing an app on Laravel or Symfony then you certainly are familiar with a file named as .env file which is present in your root folder of Laravel or Symfony directory. We use this file to store secret information about our app including app_key, database connection, payment gateway information or mailer information etc. Or to put in simple words we do not want anyone unauthorized person to have access to this .env file. So how to protect .env file from public access?

How Do You Protect env File From Public

In simple words your env is accessible from the outside world using the following lines when you type them in the google search engine you will get the certain result as follows:-


DB_USERNAME filetype:env

APP_DEBUG filetype:env

DB_PASSWORD filetype:env

And so on..

The reason for these unsecured .env files can be:-

  1. Misconfigured Shared Hosting
  2. The .env file has the wrong access rights

Shared Hosting

To configure your shared hosting for .env file make sure that only the public folder is accessible from outside and not anything of your root folder can not be accessed from outside. If you are technical enough to change these setting on your own then good otherwise Go for VPS.

Wrong Access Rights For .env

One of the reasons for unsecured .env could be the wrong access rights for your .env file. Make sure that CHMOD for your .env file should be 400 or 440 so that it can not be accessed from outside the public folder.

One of the ways to avoid .env access is to use htaccess as follows:-

Create .htaccess file in your Root Directory and put the following Code.

#Disable index view
options -Indexes
#hide a Specifuc File
<Files .env>
order allow,deny
Deny from all
</Files>

 

Also, protect dotfiles with this

# Block access to dot file
location ~ /. {
    deny  all;
}

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 writing about this. If you really liked this article then comment below and let us have a chit chat on the topic. Cheers! Happy Coding

This post is submitted by one of our members. You may submit a new post here.

Related Tricks