Exposed .env, .git and configuration files on your own web servers are one of the cheapest ways for a cloud key, database password or API token to leave your organisation, and finding them first is a routine you can run every week. This guide covers how to inventory the hosts you own, check them for files that should never be served, block those paths at the web server, and treat anything you find as a credential incident. It is written for application security, platform and identity teams working on their own estate with written authorisation. It is not a guide to scanning systems you do not own.
If you have already confirmed a public .git directory, go straight to the Exposed .git Directory Response guide, which covers containment and evidence. This page sits before that one: it is about finding the problem across many hosts before anyone else does.
Key takeaways
- Mass scanning for
/.envis real and automated. Unit 42 reported a campaign that targeted at least 110,000 domains and used AWS access keys from exposed.envfiles as its way in. - Start from an inventory of every hostname and virtual host you own, not from a list of "important" sites. Forgotten staging and marketing hosts are where these files usually sit.
- Check a short, fixed list of sensitive paths against your own hosts, and judge each response by status code, size and content type rather than by status code alone.
- Block dotfiles and backup extensions at the web server or edge as a default rule, then move secrets out of the web root so the block is a second line, not the only one.
- Any credential found in a served file is compromised. Rotate it, review its use in logs, and find the owner of the non-human identity behind it.
Why exposed configuration files matter for non-human identities
A .env file is a plain text list of environment variables. In many frameworks it holds the database URL, the cloud provider access key, the payment provider secret, the mail service API key and the signing key for sessions. Each of those values is the credential of a non-human identity: a service account, an IAM user, an OAuth client or an API key. When the file is served over HTTP, every one of those identities is exposed in a single request.
The Unit 42 analysis of a large scale cloud extortion operation, published in August 2024, shows how this is exploited at scale. The attackers' tooling requested /.env on each domain in a target list and extracted cleartext credentials. Unit 42 reported more than 230 million unique targets in the attackers' scan lists, over 90,000 unique variables collected from exposed files, and around 7,000 access keys tied to cloud services. Unit 42 also notes that the exposure came from victim misconfiguration rather than from flaws in the cloud or SaaS products involved. Once inside, the attackers used the first key to create an IAM role, attach an administrator policy and move on to data theft and extortion.
The lesson for defenders is simple: if an automated campaign can request one path on hundreds of millions of hosts, you should be able to request a few dozen paths on the hosts you own. For the wider context on keeping secrets out of these files, see Environment Variables and .env Files.
Step 1: build the inventory of hosts you own
You cannot check what you have not listed. The inventory should include every name that resolves to something you operate, and it should be refreshed on a schedule because new hosts appear every sprint.
- DNS zones you control. Export records from your authoritative DNS provider for each registered domain. Include A, AAAA and CNAME records, and note CNAMEs that point at platform or hosting providers.
- Cloud load balancers, CDN distributions and app platforms. List the public endpoints from each cloud account and each platform as a service tenant. Default platform hostnames are often reachable even when a custom domain is in front.
- Web server virtual hosts. On each server, list the configured server names. One IP address may serve several sites, and a request with the wrong Host header may land on a default site with a different document root.
- Certificate records. Your certificate management tooling lists names you have requested certificates for, which is a useful cross check against DNS.
- Owner and environment. Record the owning team and whether the host is production, staging, test or preview. Staging and preview hosts are frequently built from the same repository with less hardening.
An external attack surface management tool can automate much of this, and the Attack Surface Management Guide covers how to run that programme. Whatever the tool, confirm each host is yours before you test it. Shared hosting and third party platforms may need the provider's permission.
Step 2: define the paths you will check
Keep the list short, fixed and versioned, so that results are comparable from week to week. Group paths by what they reveal.
| Group | Example paths | What a hit exposes |
|---|---|---|
| Environment files | /.env, /.env.local, /.env.production, /.env.backup | Database URLs, cloud keys, API tokens, session signing keys |
| Version control metadata | /.git/HEAD, /.git/config, /.svn/entries, /.hg/ | Source code history, remote URLs that may embed tokens, committed secrets |
| Framework configuration | /config.php.bak, /wp-config.php~, /appsettings.json, /web.config.old | Connection strings and keys in a readable form |
| Deployment and CI files | /docker-compose.yml, /.npmrc, /.aws/credentials | Registry tokens, cloud profiles, service passwords |
| Archives and dumps | /backup.zip, /site.tar.gz, /dump.sql | Whole application trees or databases |
Add paths from your own stack. If your teams use a particular framework, include its configuration file names and the editor backup suffixes your developers use. Remove paths that never apply to you, so the noise stays low. Store the list in a repository with change history; it is part of your control evidence.
Step 3: check your hosts safely
The check itself is a set of ordinary HTTP GET requests. The care is in how you run it and how you read the results.
- Authorise and announce. Get written approval for the host list and the schedule, and tell the teams who run your web application firewall and monitoring, so they do not treat the checks as an attack.
- Use a fixed, identifiable source. Run from a known address and a clear User-Agent string. That makes your own traffic easy to filter in logs and easy to explain.
- Rate limit. A few requests per second per host is enough. You are checking a few dozen paths, not crawling.
- Send the right Host header. Request each hostname by name over HTTPS and also check the default site on each public IP address, because a misrouted request can reach a different document root.
- Do not download whole files into shared systems. Record the status code, size, content type and a hash or the first line. If a file looks like it contains secrets, stop, record the finding and move to the response steps. Do not paste secret values into tickets or chat.
Reading the results is where most programmes go wrong. Many sites return 200 with a friendly "page not found" body for every path, and single page applications often return the same HTML shell for any URL. Treat a result as a likely hit only when the response differs from that site's normal not found response. Useful signals include a text/plain or application/octet-stream content type where you expected HTML, a body that starts with ref: refs/ for .git/HEAD, or lines in KEY=value form for an environment file. A quick baseline request for a random, nonexistent path on each host gives you the comparison you need.
Step 4: block sensitive paths at the web server
A block rule turns a whole class of exposure into a non-event. Apply it as a default in your base configuration so every new site inherits it, then confirm with the Step 3 check that it works.
nginx
The nginx core module documentation explains that regular expression locations use ~ for case sensitive and ~* for case insensitive matching, and that the first matching regular expression wins unless an exact (=) or ^~ prefix location takes precedence. The same page documents the internal directive, which makes a location usable only for internal requests so that external requests receive 404. An illustrative rule that hides dotfiles and common backup suffixes:
location ~ /\.(?!well-known) { internal; }
location ~* \.(bak|old|orig|swp|sql|tar|gz|zip)$ { internal; }
Two cautions from the same documentation. First, because regular expression locations are checked in configuration order and a ^~ prefix stops the search, an earlier location block can bypass your rule; place these rules early and test them. Second, nginx matches against a normalised URI, decoding percent encoding and resolving dot segments, which helps, but you should still test encoded variants against your own hosts. The .well-known exception keeps certificate validation and similar standard paths working.
Apache HTTP Server
The Apache core documentation describes <FilesMatch>, which limits enclosed directives by filename using a regular expression, and <DirectoryMatch>, which matches directory paths. The mod_authz_core documentation states that Require all denied denies access unconditionally. An illustrative pattern for the server or virtual host configuration:
<FilesMatch "^\.|\.(bak|old|orig|swp|sql)$"> Require all denied </FilesMatch>
<DirectoryMatch "/\.(git|svn|hg)"> Require all denied </DirectoryMatch>
The core documentation also recommends keeping AllowOverride None at the root and enabling overrides only where needed. That matters here: if .htaccess files are allowed everywhere, a developer can weaken a rule you set centrally. Put these blocks in the main configuration, not in .htaccess.
Edge and platform rules
If traffic passes through a CDN, load balancer or web application firewall you control, add an equivalent rule there as well. It protects origins you do not yet know about and gives you a log of who is requesting these paths. Keep the server rule too, because the edge can be bypassed if the origin is reachable directly.
Step 5: remove the root cause
Blocking is a control on delivery. The root cause is that a secret file sat inside a directory the web server could serve. Fix that in the build and deploy process.
- Keep the document root separate from the application root. Serve only a
publicorstaticdirectory, so configuration and source live one level above it. - Do not deploy by copying a working tree. Deploy built artefacts, not a checkout, so
.gitand editor files never reach the server. Add.envand similar files to the ignore rules used by your build and container image steps. - Deliver secrets at runtime. Use a secrets manager, a platform secret store or workload identity rather than a file on disk. The Environment Variables and .env Files guide sets out the options.
- Prefer short lived credentials. Unit 42's recommendations include using temporary IAM roles instead of long term access keys and applying least privilege to role creation permissions. A short lived credential found in a file has far less value to whoever finds it.
- Check debug and diagnostic endpoints at the same time. The same hosts that serve configuration files often expose debug pages. See the Exposed Debug Modes Guide.
Step 6: respond when you find a live exposure
Treat every secret in a served file as known to an attacker. You cannot prove nobody else requested the file, especially given automated campaigns that request /.env across huge target lists.
- Block the path immediately using the rules above, then confirm with a fresh request.
- Preserve evidence. Keep the web server and edge access logs for the period the file was reachable. Look for requests to the path from sources other than your own checker.
- List every credential in the file and map each to its non-human identity, its owner and the systems it can reach. Record names, not values.
- Rotate or revoke each credential, starting with cloud provider keys and anything with administrative rights. Confirm the old value no longer works.
- Review use of each credential in the provider's audit logs for the exposure window. Unit 42 recommends enabling cloud audit logging and keeping at least 90 days of logs, which is what makes this review possible.
- Fix the deploy path that put the file there, and add a regression check to the pipeline.
For exposed version control metadata, follow the Exposed .git Directory Response guide, because a .git directory can expose the full history, including secrets that were removed from the current code long ago.
Step 7: make it continuous
A one off sweep finds today's problems. New hosts, new frameworks and new deploy scripts will create tomorrow's.
- Run the Step 3 check on a schedule against the full inventory, and on every new host when it first appears in DNS or the cloud inventory.
- Add a pipeline test that requests the sensitive path list against each newly deployed environment and fails the deployment on a likely hit.
- Alert on requests to blocked paths at the edge. A spike tells you that someone is scanning you; a request from inside your network tells you a tool or script needs fixing.
- Report two simple measures: the share of inventoried hosts checked in the last seven days, and the number of open findings older than one day.
Common failure patterns
- Checking only production. Staging, preview and old marketing sites are built from the same code and get less attention.
- Trusting status codes. A site that returns 200 for everything hides real hits in noise, and a site that returns 403 for a dotfile has still told you the file exists.
- Relying on
.htaccessor per site rules. A central rule in the main configuration is harder to undo by accident. - Blocking without rotating. Hiding the file does not change the fact that the secrets inside it were readable.
- Pasting secrets into tickets. The response process spreads the secret further than the original exposure.
- No owner for the credential. Rotation stalls when nobody knows which service uses a key. See How to assign owners to orphaned service accounts.
Practitioner checklist
- Maintain a refreshed inventory of every hostname, virtual host and platform endpoint you own, with an owner and environment for each.
- Keep a versioned list of sensitive paths covering environment files, version control metadata, configuration backups, deployment files and archives.
- Run authorised, rate limited checks from an identifiable source, comparing each response with a baseline not found response.
- Apply central block rules for dotfiles and backup suffixes in nginx, Apache or your edge, and test them after every configuration change.
- Keep configuration and secrets outside the document root and deploy built artefacts, not working trees.
- Treat every exposed secret as compromised: rotate, review audit logs and record the owner.
- Add a pipeline check and edge alerting so new exposures are caught within a day.
Standards and references
- Unit 42 (Palo Alto Networks): large scale cloud extortion operation using exposed .env files, August 2024
- nginx: Module ngx_http_core_module (location and internal)
- Apache HTTP Server 2.4: core features (FilesMatch, DirectoryMatch, AllowOverride)
- Apache HTTP Server 2.4: mod_authz_core (Require all denied)
- MITRE ATT&CK: Credentials In Files (T1552.001)
- MITRE: 2025 CWE Top 25 Most Dangerous Software Weaknesses
- CISA and NSA: Top Ten Cybersecurity Misconfigurations (AA23-278A)
- NIST: SP 800-53 Rev. 5 (CM-7 Least Functionality, IA-5 Authenticator Management)
Related NHI Mgmt Group resources: Exposed .git Directory Response · Environment Variables and .env Files · Exposed Debug Modes Guide · Attack Surface Management Guide