Site icon Web Niraj

Hiding .env Files using .htaccess

A common attack vector to compromise Laravel applications (and indeed others) is to access the application’s config file, which could contain credentials to services like MySQL, APIs and other sensitive resources. This is especially important if you haven’t protected the .env files correctly.

Luckily, if you’re using Apache, you can use .htaccess files to set up a blanket rule that blocks access to any .env files on your system from direct access. This works best if you are able to edit the
/etc/apache2/conf-available/security.conf
file on your server so that it applies server wide. But if this cannot be achieved, you can also do this in a .htaccess file placed in your application director.

The content you need to add to the security.conf or .htaccess file is:

Code and Implementation Instructions

  1. Create or locate your security.conf or .htaccess file.
    • If you don’t have one, create a new file named .htaccess in the root directory of your web application.
    • If you already have an .htaccess file, open it for editing.
    • If editing the security.conf file, you can usually find it at
      /etc/apache2/conf-available/
      .
  2. Add the above code snippet within the file
  3. Enable the security.conf file, if not previously used, using sudo a2enconf security
  4. Save the file and restart Apache, if editing the security.conf file

Explanation

Important considerations

Exit mobile version