Table of contents

protect .env file in laravel

If you are using shared hosting for your Laravel project and the .env file is accessible in URL. Then we need to protect it using .htaccess so that no one can see your application credentials.

 

Sometimes if we use shared hosting the .ENV file is accessible in the browser may be because of your server configuration. But the easiest way to hide it is in the .htaccess configuration.

 

Open your public/.htaccess file and add the following lines.

 

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

 

Here is the complete .htaccess code.

 

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

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

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

 

I hope it helps. Thank you for visiting.