Search

How to make secure or hide .env file from public access in Laravel

How to Secure or Hide .env File from Public Access in Laravel

The .env file in Laravel contains sensitive information and should never be exposed to public access. Here’s a guide to ensure your .env file stays secure.

1. Default Laravel Configuration

By default, Laravel is set up to deny direct access to files like .env within the public directory. The file is stored in the root directory of the project, which is not accessible via web servers.

2. Web Server Configuration

Apache Configuration (.htaccess)

If you're using Apache, make sure that your .htaccess file in the root directory contains the following to deny access to .env files:

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

Nginx Configuration

If you're using Nginx, add the following block in your Nginx configuration file (usually /etc/nginx/sites-available/default or similar):

location ~ /\.env {
    deny all;
}

3. Proper File Permissions

Ensure that your environment file has the correct file permissions. Run the following command in your terminal:

chmod 640 .env

This sets the permissions so that only the owner can read and write to the file, and the group can only read it. Other users cannot access it.

4. Use Environment Variables in Hosting

If possible, use hosting services that support environment variables directly, which avoids the need to use a .env file in production.

5. Framework and Middleware Protection

Laravel itself provides middleware that can help in securing your routes and controllers against unauthorized access. Always keep your framework, libraries, and middleware updated to the latest versions to benefit from the latest security patches.

For more information, visit the official Laravel documentation.

By following these steps, you can ensure that your .env file remains secure and hidden from public access.

Sys Admin

Sys Admin

I am a Red Hat Certified Engineer (RHCE) and working as an IT Professional since 2012...