How to secure .env file in laravel 5.4?

12,098

Solution 1

Remember that once your server is configured to see the public folder as the document root, no one can view the files that one level down that folder, which means that your .env file is already protected, as well your entire application. - That is the reason the public folder is there, security. - The only directories that you can see in your browser if you set the document root to the public folder is the folders that are there, like the styles and scripts.

You can make a test like this:

Enter in your project directory with the terminal and hit this:

php -t public -S 127.0.0.1:80

The -t means the document root, where the PHP built-in web server will interpreter as the document root. - see bellow:

-t <docroot> Specify document root <docroot> for built-in web server.

Now try to access the .env file, and you will see that you will get a 404 that the resource as not found.

Of course it's just an example, you will need to configure your sever to do the same.

Solution 2

you can add following code to your .htaccess (make sure your .htaccess file should be in root folder not in public)file to deny the permission of .env file

  <FilesMatch "^\.env">
    Order allow,deny
    Deny from all
 </FilesMatch>

Solution 3

Simply you add below code to your .htaccess file to set permission of .env and composer.json file.

  <Files .env>
    Order allow,deny
    Deny from all
  </Files>

  <Files composer.json>
    Order allow,deny
    Deny from all
  </Files>

And below line for disabling directory browsing

Options All -Indexes

Solution 4

Nobody can view these files via the browser because the root of your website is located at /public and the composer.json and .env files are outside of this scope.

The only way to view these files is actually connecting to the web server and going to the corresponding folder.

Share:
12,098
Nileshsinh Rathod
Author by

Nileshsinh Rathod

Software Developer @ DevDigital Vadodara Pvt. Ltd. I've been programming professionally for more than 7 years, most recently with a focus on Laravel and ReactJs.

Updated on June 16, 2022

Comments

  • Nileshsinh Rathod
    Nileshsinh Rathod about 2 years

    I am Working with laravel 5.4. And i have problem with .env and composer.json file. Anyone can access from any browser and anyone can see my database credentials so please help me to protect this files.

  • Jerodev
    Jerodev about 6 years
    In this case your webserver isn't configured correctly
  • Ali
    Ali over 5 years
    this worked for me, when i created another .htaccess file in my project folder(outside of public folder).