Tran Nghi's Site  - Make notes and share experience

Protect your .env file on your app projects

This post is also available in: English

.env file is used to store database and email credentials. But when I’m opening https://yourdomain/.env the .env file content is shown in browser.

How to protect it from retrieving by web browser?

in production domain should be pointed to laravel project public folder where index.php file is, once it is done nobody can access .env file. if you are uploading project to showing demo to client don’t upload .env file you can set evn parameter in .htaccesss file.

Eg: vi .htaccess

  SetEnv APP_ENV local
  SetEnv APP_DEBUG true
  SetEnv APP_KEY app_keyasfassafas

  SetEnv DB_HOST localhost
  SetEnv DB_DATABASE db_name
  SetEnv DB_USERNAME root

  SetEnv CACHE_DRIVER file
  SetEnv QUEUE_DRIVER sync

Another way, you can set the access permission to retrict web browser reading your file, by also using .htaccess. It works also in localhost and Live server.

  ## Disable Directory listing
  Options -Indexes

  ## block files which needs to be hidden, specify .example extension of the file
  <Files ~ "\.(env|json|config.js|md|gitignore|gitattributes|lock)$">
    Order allow,deny
    Deny from all

or just like my simple .htaccess setup:

  ## Hide a specific file
  <Files .env>
    Order allow,deny
    Deny from all


How about yours to solve this matter!?