How to secure .env file in Laravel

2019-10-22 11:27:43 Deelip Laravel

Secure .Env File In Laravel

If your are a developer and developing any app on Laravel or Symfony then you certainly is 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 unauthorised person to have access to this .env file. So how to proetct .env file from public access?

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

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

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

  • Misconfigured Shared Hosting
  •   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 form 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 reson 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 way to avoid .env access is to use htaccess as follows:-

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

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

Also, protect dot files 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.

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

Related Tricks