Secure .env File in Laravel on Apache and Nginx

In the root of any Laravel folder, there should be .env file that contains various settings, in KEY=VALUE pair format.

This file is critical because it contains different environments’ definitions (dev, stage, production) and a security risk in the event an intruder gains access to the file. It’s important to keep this file secure and not commit it to your version control system.

If you don’t configure it well, anyone can access yourdomain.com/.env file and read its content.

Following these steps to secure the file:

Setup domain’s root folder

The proper way to run a Laravel app is to map a domain to the public folder. After that, no one can view the files in the root folder of Laravel, which means that your.env file is already protected, as well as your entire application.

Ignore in source control

As I mentioned above, this file is different from each environment, so it is better to avoid committing this file. This would be a security risk in case there is a data breach in your source control repository.

Ensure that the .env file is added to your .gitignore file so that it’s not accidentally committed to your version control system. If you’re using a hosted version control service like GitHub, ensure that the .env file is not accidentally uploaded to the repository.

Block access

For Apache

Adding these lines in your .htaccess file to block access to .env file.

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

For Nginx

Locate your Nginx configuration file, usually found in /etc/nginx/sites-available or /etc/nginx/nginx.conf.

Open the config file for editing and add the following line within your server block.

location ~ /\.env {
    deny all;
}

Move the .env file outside of the project root directory

By default, the .env file is located in the project root directory. You can move it outside the project root directory and update the APP_ENV variable in the .env file to reflect the new path. This way, even if someone gains access to your project files, they won’t have access to the .env file.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close