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 file on your server so that it applies server wide. But if this cannot be achieved, you can also do this in a
/etc/apache2/conf-available/security.conf.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
- Create or locate your
security.confor.htaccessfile.- If you don’t have one, create a new file named
.htaccessin the root directory of your web application. - If you already have an
.htaccessfile, open it for editing. - If editing the
security.conffile, you can usually find it at.
/etc/apache2/conf-available/
- If you don’t have one, create a new file named
- Add the above code snippet within the file
- Enable the
security.conffile, if not previously used, usingsudo a2enconf security - Save the file and restart Apache, if editing the
security.conffile
Explanation
<Files .env>: This directive specifically targets the.envfile.Order allow,deny: Sets the order in which allow and deny directives are evaluated.Deny from all: Explicitly denies access to the.envfile from all clients. This will display a 403 error to users trying to access.envfiles.
Important considerations
- Server configuration: This solution assumes you’re using an Apache web server. Other web servers might have different configuration mechanisms.
- Additional security: Consider other security measures like placing your
.envfile outside of the publicly accessible web directory if possible. - Testing: After implementing this, attempt to access your
.envfile directly through your browser to confirm it’s blocked. You should see a “403 Forbidden” error.
