image from — www.immuniweb.com

Change Environment file name in Laravel

Do you know that google crawled your website and index everything available including your .env file?. Environment file in Laravel located in root project which stores all important information and credentials like database password, email configurations and other env variables. Without proper permission, your system will be compromise badly…

But, do you know that your .env file can be rename? In term of security, you might be thinking of it right? And you might want to hide the .env file to some where hidden in your project directory.

Lately, my web application firewall been detecting several request requesting like this “https://website.com/.env” so many times. But, Im not worrying much because i have proper permission and WAF (confident level 9999 😂).

Let’s get started

If you open the app.php inside bootstrap folder, you will find this at the first line

$app = new \App\Extensions\Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

Open the Application.class and go down a little bit, you will see this variables

/**
* The custom environment path defined by the developer.
*
*
@var string
*/
protected $environmentPath;

/**
* The environment file to load during bootstrapping.
*
*
@var string
*/
protected $environmentFile = '.env';

There is two way we can adjust this, whether we create new extended Application class or just use the existing setter in app.php

Method 1: Extend

Create a new Application class and extend it with \Illuminate\Foundation\Application

class Application extend App {
protected $environmentFile = '.project.env';
}

Put your desire env file name there and re-serve again. If you want to change the path,

class Application extend App {
protected $environmentFile = '.project.env';
protected $environmentPath = 'credentials';
}

The application will read as credentials/.project.env.

Method 2: Use setter

There are setter method in Application class that we can use to modify directly

$app = new \App\Extensions\Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

// $app->useEnvironmentPath('credentials');
$app->loadEnvironmentFrom('.project.env');

Notes

But, i don’t know it’s a bug or not, if you change the path, you are force to use config:cache. Else, it will not working. If only change the name of the file, then no need to cache it.

That’s all. Thanks for your time

~~~ Happy Working~~~

Software Engineer at Teratotech.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store