DEV Community

Roman Shneer
Roman Shneer

Posted on

Laravel Application with Encrypted .env

This guide explains how to securely run a Laravel application (version 12) in a production environment using Apache, with an encrypted .env file.

Overview

In production, it’s crucial to protect sensitive information found in the .env file. This method encrypts your configuration file and utilizes an encryption key stored in an environment variable for security.

Steps to Run Laravel with Encrypted .env

Step 1: Encrypt the .env File

Execute the following command in your terminal to prepare the encoded file:

php artisan env:encrypt
Enter fullscreen mode Exit fullscreen mode

Note: Remember your encryption key and cipher settings as you'll need them later.

Step 2: Set Environment Variable in Apache

Open your httpd.conf (or .htaccess) file and add the following line to set the encryption key:

SetEnv LARAVEL_ENV_ENCRYPTION_KEY your_key_here
Enter fullscreen mode Exit fullscreen mode

Afterwards, restart your web server:

sudo systemctl restart apache2
Enter fullscreen mode Exit fullscreen mode

Step 3: Decrypt the .env File in Laravel

Add the following code snippet in /bootstrap/app.php before the line where the application is configured:
Application::configure(....

//START ENV DECODING

use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Str;
$cipher = 'aes-256-cbc'; //change your cipher
$filename = '.env.encrypted';//change your encrypted file

$key = getenv('LARAVEL_ENV_ENCRYPTION_KEY'); // Retrieve the encryption key from the environment variables

$encryptedContent = file_get_contents("../{$filename}");
if (Str::startsWith($key, $prefix = 'base64:')) {
    $key = base64_decode(Str::after($key, $prefix));
}

$decrypted_text = (new Encrypter($key, $cipher))
    ->decrypt($encryptedContent);

$rows = array_filter(
    explode("\n", $decrypted_text),
    fn($r) => !empty(trim($r))
);

$rows = array_map(
    fn($r) => array_map(
        fn($r) => trim(
            str_replace('"', '', $r)
        ),
        explode("=", $r)
    ),
    $rows
);

foreach ($rows as $row) {
    $_SERVER[$row[0]] = $row[1];
}

//END ENV DECODING
Enter fullscreen mode Exit fullscreen mode

Step 4: Final Cleanup

By following these steps, you can run your Laravel application securely with an encrypted .env file. Ensure you keep your encryption key safe to maintain the integrity of your sensitive information.

Backup and Delete the Original .env File

Top comments (0)