
Environment Variable Best Practices: .env Files and Secrets
Environment variables and .env files are essential security measures that keep sensitive data like API keys and database credentials out of your codebase. Properly managing these secrets prevents accidental exposure and follows security best practices that professional developers rely on. In this guide, we’ll cover everything you need to implement secure environment variable handling in your WordPress projects.
Understanding .env Files and Their Purpose
.env files are plain text configuration files that store environment-specific variables outside your main codebase. Instead of hardcoding sensitive information directly into your PHP files, you reference variables defined in .env, which remains on your server and never gets committed to version control.
In WordPress, this means storing database credentials, API keys for third-party services, authentication tokens, and other sensitive data in .env rather than in wp-config.php or theme functions. When your application starts, it loads these variables into the environment, making them accessible throughout your code without exposing them in git repositories.
The primary benefits include:
- Security: Sensitive data stays off version control systems
- Flexibility: Change values between development, staging, and production without code changes
- Team collaboration: Share .env.example without actual secrets
- Compliance: Meet security standards and regulations like PCI DSS
- Auditability: Track which variables are used across your application
WordPress developers using modern hosting, headless implementations, or advanced plugins benefit significantly from implementing proper .env file management from the start.
Setting Up and Configuring .env Files Correctly
Proper .env configuration begins with understanding the structure and implementation. Here’s how to set up your WordPress environment variables securely.
Step 1: Create Your .env File
In your WordPress root directory (alongside wp-config.php), create a .env file with your environment variables:
DB_NAME=wordpress_db
DB_USER=db_user
DB_PASSWORD=your_secure_password
DB_HOST=localhost
DB_CHARSET=utf8mb4
WP_ENV=development
WP_DEBUG=true
WP_SITEURL=http://localhost
WP_HOME=http://localhost
AUTH_KEY=your_unique_auth_key
SECURE_AUTH_KEY=your_unique_secure_key
LOGGED_IN_KEY=your_unique_logged_in_key
NONCE_KEY=your_unique_nonce_key
Step 2: Load Variables in wp-config.php
Use a package like phpdotenv to load your .env file. Install it via Composer:
composer require vlucas/phpdotenv
Then in wp-config.php, add at the very top:
if (file_exists(__DIR__ . '/.env')) {
$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();
}
define('DB_NAME', $_ENV['DB_NAME'] ?? 'wordpress');
define('DB_USER', $_ENV['DB_USER'] ?? 'root');
Step 3: Add .env to .gitignore
Prevent accidental commits by adding to your .gitignore:
.env
.env.local
.env.*.local
Step 4: Share a Template
Create a .env.example file showing the structure without secrets:
DB_NAME=
DB_USER=
DB_PASSWORD=
DB_HOST=localhost
WP_ENV=development
WP_DEBUG=false
This allows team members to copy and fill in their own values without exposing live credentials.
Security Best Practices for Secret Management
Beyond basic .env file setup, implementing security best practices protects against various attack vectors and misconfigurations.
Use Strong, Unique Values
Every secret should be complex and unique. For WordPress security keys and salts, use the official WordPress API generator. For API keys and passwords, consider using random generators with sufficient entropy (at least 32 characters for sensitive values).
Implement Environment-Specific Configurations
Use the WP_ENV variable to load different values based on your environment:
if ($_ENV['WP_ENV'] === 'production') {
define('WP_DEBUG', false);
define('SCRIPT_DEBUG', false);
} else {
define('WP_DEBUG', true);
define('SCRIPT_DEBUG', true);
}
Restrict File Permissions
On your server, set restrictive permissions on the .env file:
chmod 600 .env
This ensures only the file owner can read it, preventing other users on shared hosting from accessing your secrets.
Rotate Secrets Regularly
Implement a rotation schedule for sensitive credentials every 90-180 days. This limits exposure window if a secret is compromised. Update your .env file and redeploy without code changes.
Monitor for Leaks
Use services to scan public repositories for exposed credentials. If you discover a leak, immediately rotate affected secrets and audit access logs.
Use Environment-Specific Secret Management
For production environments, consider using dedicated secret management services rather than .env files. These services provide encryption at rest, access controls, and audit trails.
How to Use Our Development Tools
When managing multiple environments and secrets, tracking which variables are needed becomes complex. Our Environment Variable Calculator helps you organize, validate, and document all required variables across your projects. The tool generates standardized .env templates, validates naming conventions, and ensures consistency across your development team—saving time and reducing configuration errors.
Frequently Asked Questions
Should I commit .env files to version control?
Never commit production .env files. Always add .env to .gitignore. Instead, commit .env.example with placeholder values so team members know what variables are needed. This approach provides documentation while protecting secrets.
Can I use .env files on shared hosting?
Yes, .env files work on shared hosting. Ensure you set proper file permissions (600) and place the file outside the public_html directory if possible. Verify your hosting provider allows Composer-based packages for loading .env files, or implement an alternative method like a custom configuration loader.
How do I handle environment variables in Docker containers?
Docker allows
- 1Password Business — Comprehensive secrets management and credential storage solution that directly addresses the post’s focus on securing API keys and database credentials
- HashiCorp Vault — Enterprise-grade secrets management platform for securely storing and rotating environment variables and sensitive data across development teams
- AWS Secrets Manager — Cloud-native secrets management service that integrates with applications to manage database credentials, API keys, and other sensitive environment data
Related reading: Environment Variable Generator: Manage Config Files Safely.
Related: Security best practices for protecting your GitHub repositories from unauthorized access