Exposed .env Files: The #1 Secret Leak on the Internet
A single HTTP request to /.env can expose every credential your application uses — database passwords, API keys, mail server credentials, encryption keys, and more. This is the most common and most dangerous misconfiguration on the web, and millions of websites are vulnerable right now.
What Is a .env File?
The .env file (dotenv) is a convention for storing environment-specific configuration outside of source code. Popularized by the Twelve-Factor App methodology and libraries like dotenv for Node.js, python-dotenv for Python, and vlucas/phpdotenv for PHP, the pattern is simple: store sensitive configuration in a .env file that is loaded at application startup but never committed to version control.
# Typical .env file contents
APP_ENV=production
APP_KEY=base64:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
APP_DEBUG=false
DB_HOST=db.internal.example.com
DB_PORT=3306
DB_DATABASE=production_db
DB_USERNAME=app_user
DB_PASSWORD=s3cur3_p4ssw0rd_h3re
MAIL_HOST=smtp.mailgun.org
MAIL_USERNAME=postmaster@example.com
MAIL_PASSWORD=mail_api_key_here
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
AWS_DEFAULT_REGION=us-east-1
STRIPE_SECRET_KEY=sk_live_xxxxxxxxxxxxxxxxxxxx
REDIS_PASSWORD=redis_pass_123
The .env file is the master key to your entire application. If an attacker can read it, they have access to your database, your email service, your cloud infrastructure, your payment processor, and every other service your application connects to.
How .env Files Get Exposed
1. Web Server Misconfiguration
This is the most common cause. When a web application's document root is set to the project root directory instead of a public/ or www/ subdirectory, the .env file becomes directly accessible via HTTP. An attacker simply requests https://example.com/.env and the web server serves the file as plain text.
This happens frequently with:
- Laravel applications where the vhost points to the project root instead of
/public - Node.js/Express applications with
express.staticserving the project directory - Shared hosting where the document root cannot be configured to a subdirectory
- Docker deployments where the Dockerfile copies the entire project into the web root
2. Missing .gitignore Entry
If .env is not in your .gitignore file (or the .gitignore was created after the first commit), the file gets committed to version control. Even in private repositories, this is dangerous — any developer with access can see production credentials, and a single compromised developer account exposes everything. Use our .gitignore Generator to ensure your ignore rules are complete.
3. Backup Files Left in Place
System administrators and editors create backup files that are also served by the web server:
# All of these are commonly accessible
/.env.backup
/.env.bak
/.env.old
/.env.save
/.env.production
/.env.staging
/.env.local
/.env~
/.env.swp # vim swap file
/.env.swo # vim swap overflow
Even if you have blocked access to /.env, the backup variants often slip through because they do not match the same blocking rule.
4. Directory Listing Enabled
When Apache's Options +Indexes or Nginx's autoindex on is enabled, visiting a directory shows all files in it — including .env. An attacker does not even need to guess the filename; they simply browse the directory listing.
5. Deployment Artifacts
CI/CD pipelines that copy the entire project directory (including .env) to a web server, or Docker images that include .env in the build context, can expose secrets. Some platforms (like Heroku) provide environment variable management that avoids .env files entirely, but many self-hosted deployments still rely on files.
Real-World Breach Examples
Exposed .env files are behind some of the largest breaches in recent years:
- Twitch (2021): A server misconfiguration exposed internal Git repositories containing
.envfiles with AWS credentials, leading to a massive data breach including source code and creator payment data. - Laravel framework default: In 2017, researchers found over 1,800 Laravel applications with publicly accessible
.envfiles via a single Shodan search. Many contained database credentials, Stripe keys, and AWS secrets. - Ongoing at scale: A 2025 Censys study found approximately 90,000 publicly accessible
.envfiles on the internet. Security researcher Shubham Shah demonstrated that simple Google dorking (filetype:env DB_PASSWORD) returns thousands of results.
Attackers do not need sophisticated tools to find exposed .env files. A single search engine query can reveal thousands of vulnerable sites. Automated scanners probe for /.env as one of their first checks.
Is Your .env File Publicly Accessible?
Our Exposure Checker tests for exposed .env files, backup variants, and other sensitive configuration files on your domain. Find out in seconds.
Check Your Domain NowHow to Detect Exposed .env Files
Manual Check
The simplest test is to request the file directly:
# Check for .env exposure
curl -s -o /dev/null -w "%{http_code}" https://yourdomain.com/.env
# If you get 200, the file is exposed. If 403 or 404, it's blocked.
# Also check common variants:
for f in .env .env.backup .env.bak .env.old .env.production .env.local .env.staging; do
code=$(curl -s -o /dev/null -w "%{http_code}" "https://yourdomain.com/$f")
echo "$f: $code"
done
Automated Scanning
For a thorough check across multiple paths and file patterns, use the SecureBin Exposure Checker. It tests for .env files along with dozens of other sensitive paths including .git/config, wp-config.php, debug endpoints, and more — all in a single scan.
Search Engine Detection
Check if search engines have indexed your .env file:
# Google dorking for your domain
site:yourdomain.com filetype:env
site:yourdomain.com inurl:.env
# Broader searches (use responsibly)
"DB_PASSWORD" filetype:env
"APP_KEY" "base64:" filetype:env
How to Fix and Prevent .env Exposure
1. Set the Correct Document Root
The most important fix: ensure your web server's document root points to a public subdirectory, NOT the project root. The .env file should be at least one directory level above the web root.
# Correct directory structure
/var/www/myapp/
.env <-- NOT accessible from web
composer.json
app/
config/
public/ <-- Document root should point HERE
index.php
css/
js/
2. Block .env in Your Web Server Config
Apache (.htaccess):
# Block all dotfiles (.env, .git, .htpasswd, etc.)
<FilesMatch "^\.">
Order allow,deny
Deny from all
</FilesMatch>
# Or specifically block .env files
<Files ".env">
Order allow,deny
Deny from all
</Files>
# Also block common backup extensions
<FilesMatch "\.(bak|old|backup|save|swp|swo)$">
Order allow,deny
Deny from all
</FilesMatch>
Nginx:
# Block all dotfiles
location ~ /\. {
deny all;
return 404;
}
# Block backup files
location ~* \.(bak|old|backup|save|swp|swo)$ {
deny all;
return 404;
}
Use our Nginx Config Generator to create a complete configuration with security rules included.
3. Ensure .gitignore Is Correct
# .gitignore - MUST include these
.env
.env.*
!.env.example
# Also block other sensitive files
*.pem
*.key
*.p12
credentials.json
service-account.json
Use our .gitignore Generator to create a comprehensive ignore file for your stack. Also validate your existing env file syntax with our ENV Validator.
4. Remove .env From Git History
If .env was ever committed, adding it to .gitignore only prevents future commits. The file still exists in Git history. You must rewrite history to fully remove it:
# Using BFG Repo-Cleaner (recommended)
bfg --delete-files .env
# Using git filter-repo
git filter-repo --path .env --invert-paths
# After rewriting history, force-push (coordinate with your team)
git push --force-with-lease
5. Use a Secrets Manager in Production
For production environments, move beyond .env files entirely. Modern secrets management systems provide encryption at rest, access control, audit logging, and automatic rotation:
- AWS Secrets Manager / SSM Parameter Store — native AWS integration
- HashiCorp Vault — multi-cloud, dynamic secrets, automatic rotation
- Google Secret Manager — native GCP integration
- Kubernetes Secrets + External Secrets Operator — syncs cloud secrets into K8s pods
- Platform environment variables — Heroku, Vercel, Railway, Fly.io all provide built-in env var management
6. Create an .env.example File
Commit an .env.example file with placeholder values that documents required variables without exposing real secrets:
# .env.example (safe to commit)
APP_ENV=local
APP_KEY=
APP_DEBUG=true
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
What to Do If Your .env Was Exposed
If you discover that your .env file is or was publicly accessible, treat it as a full credential compromise:
- Block access immediately. Add the web server rules above and verify with
curlthat the file returns 403 or 404. - Rotate ALL credentials in the file — every database password, API key, encryption key, and access token. Do not skip any. Assume everything was read.
- Check access logs for requests to
/.envand its variants. Identify when the exposure started and which IPs accessed it. - Audit for unauthorized access using the compromised credentials. Check cloud provider logs (AWS CloudTrail, GCP Audit Logs), database query logs, and email service logs.
- Implement prevention measures: correct document root, add blocking rules, remove from Git history, set up automated scanning.
- If customer data was accessible via the exposed credentials, consult your legal team about breach notification requirements (GDPR 72-hour rule, state breach notification laws, etc.).
Frequently Asked Questions
Does adding .env to .gitignore remove it from the repository?
No. Adding a file to .gitignore only prevents it from being tracked in future commits. If the file was already committed, it remains in the Git history. You need to explicitly remove it with git rm --cached .env (to remove from tracking while keeping the local file) and then rewrite history using BFG or git filter-repo to remove it from all past commits. Read our guide on checking for exposed API keys for more on Git history cleanup.
Is it safe to use .env files in production?
It is acceptable if the file is properly protected (outside web root, blocked by server config, correct file permissions). However, for production workloads, a dedicated secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.) is strongly recommended because it provides encryption at rest, access logging, key rotation, and centralized management — none of which a plain text file offers.
How do I check if my .env file was accessed before I blocked it?
Check your web server access logs for requests to /.env and variants. In Apache: grep -i "\.env" /var/log/apache2/access.log. In Nginx: grep -i "\.env" /var/log/nginx/access.log. Look for 200 status codes — these indicate the file was successfully served. If you find any, assume all credentials in the file were compromised and rotate immediately.
Can Cloudflare or a WAF protect against .env exposure?
Yes. Cloudflare WAF, AWS WAF, and other web application firewalls can be configured to block requests to sensitive paths like /.env. However, this should be a defense-in-depth measure, not your only protection. The primary fix should be at the web server level (correct document root + blocking rules). WAF rules can be bypassed if the attacker accesses the origin server directly. Our Security Headers Guide covers additional server-level protections.
Scan Your Domain for Exposed Files
Do not wait for an attacker to find your .env file. Run a free scan with our Exposure Checker to test for exposed configuration files, debug endpoints, and 17 other security issues.
Run Free Exposure ScanThe Bottom Line
An exposed .env file is the fastest path from "misconfigured server" to "total compromise." The fix takes minutes: set the correct document root, add blocking rules to your web server, ensure the file is in .gitignore, and use a secrets manager for production. Scan your domains regularly to catch misconfigurations before attackers do.
Related tools: Exposure Checker, ENV Validator, .gitignore Generator, Nginx Config Generator, SSL Checker, and 70+ more free tools.