Environment variables and secrets: keep .env off GitHub, rotate keys
Passwords and API keys don't belong in the repository: they live on the server, in GitHub secrets or in a secrets manager, and they get rotated. Here's how.
Published on · 14 min
Database passwords and API keys should not be written into the code or into a .env file pushed to GitHub: they belong in the server's environment variables, in GitHub Actions secrets or in a secrets manager, and the repository only holds a template with no values. The reason is concrete: according to GitGuardian's State of Secrets Sprawl 2026 (March 2026), 28.65 million new secrets ended up in public GitHub commits in 2025, 34% more than the year before. And an exposed key has to be changed (the word is "rotated"), not just deleted: git remembers everything.
Secrets and environment variables, in plain words
A secret is any piece of information that opens a door: the database password, the API key for payments or artificial intelligence, access to the server. Whoever holds it acts on behalf of your company.
An environment variable is a value with a name, for example DB_PASSWORD, that the server hands to the program while it runs. The value lives in the server configuration, not in the project files.
The .env file is a convenience that sits in between: a text file with NAME=value lines that many frameworks, such as Laravel, read at startup. The problem starts when it enters the repository, the code archive with its whole history.
Server or hosting panel
the real value, which the site reads while it runs
Repository on GitHub
only the code and a .env.example template with no values
PHP code
asks for the value by name: getenv('DB_PASSWORD')
Why a .env in the repository is a risk
Git doesn't forget
Every save in git (a commit) is a complete snapshot of the project. If the .env went into a commit, deleting it today creates a new snapshot without the file, but the old ones stay: going back in the history is enough to read it again.
Bots read public repositories
On a public repository nobody needs to target you. Researchers at Palo Alto Networks Unit 42 (October 2023) deliberately published AWS access keys (Amazon's cloud) on GitHub: a group that automatically cloned public repositories found and used them within five minutes.
Private repositories travel too
"It's private anyway" is not enough. A private repository gets cloned, copied into backups, connected to outside services, sometimes made public years later. The GitGuardian 2026 report finds that companies' internal repositories are roughly six times more likely than public ones to contain secrets written in the code. And that about 28% of incidents start entirely outside repositories, in tools such as Slack, Jira and Confluence: a key pasted into a chat is the same problem.
The most worrying figure is about what happens next: of the credentials found in 2022 and confirmed as working, more than 64% still worked in January 2026. Nobody had revoked them.
I mention it because Claude Code is one of the tools I use: code written with AI moves faster, and so do the mistakes. It's one of the reasons I review every line before it goes live.
Doing it right: a repository with no values
The repository gets a .env.example file with the variable names and no real values, so whoever comes next knows what to configure. The real .env stays out thanks to .gitignore, the file that tells git what to ignore.
# .gitignore: ignore every .env file except the template
.env*
!.env.example
# .env.example: names with no values, to copy into .env and fill in
APP_ENV=production
DB_HOST=
DB_NAME=
DB_USER=
DB_PASSWORD=
STRIPE_SECRET_KEY=
Watch out: according to the git documentation, .gitignore doesn't affect files already tracked. If the .env is already in the repository, it has to be removed with this command: it leaves future commits, not past ones (see further down).
git rm --cached .env
git commit -m "Remove .env from the repository"
The Laravel 13 documentation is explicit: the .env should not be committed to source control, because anyone who got into the repository would see all the credentials.
Where to put the real values
On the server, for a PHP site
There are three routes, depending on what the server allows.
- Apache with
SetEnv. According to the Apache documentation, the directive sets a variable that the server passes on to scripts. It goes in the site configuration (the virtual host) or in an.htaccess. Watch out: if the.htaccessis in the repository, the secret ends up in there again. - PHP-FPM with
env[]. PHP-FPM is the manager that runs PHP on many servers. The PHP manual explains that lines such asenv[DB_PASSWORD] = ...go in the "pool" configuration file, and that by default (clear_env) other environment variables don't reach PHP. It needs access to the server, so a VPS or a dedicated server. - A file outside the public folder. On shared hosting the first two are often not possible. Then the values sit in a PHP file one folder above the public one, excluded from the repository: the browser can't reach it.
# PHP-FPM, pool configuration file (reload PHP-FPM after the change)
env[DB_PASSWORD] = "the-real-value"
# Apache, virtual host configuration (outside the repository)
SetEnv DB_PASSWORD "the-real-value"
<?php
// public_html/index.php: the secrets file sits one folder above the public one.
$secrets = require dirname(__DIR__) . '/config/secrets.php';
In any case: a .env inside the public folder, if the server doesn't block it, can be downloaded from the browser like any other file.
On Hostinger, for a Node.js app
For Node.js apps, Hostinger's panel (hPanel) has a dedicated section. Hostinger's guide (updated in November 2026) says Node.js apps are available on the Business and Cloud plans. The environment variables documentation (July 2026) explains that you enter them during the first deployment or later, from "Environment variables" in the site's sidebar; values are masked and saving redeploys the app so it reads them.
Note: simplified diagram of the hPanel screen, with the names used in Hostinger's English documentation (November 2026). In other interface languages the labels may be translated.
On GitHub Actions, for automatic deployment
If the site deploys itself with GitHub Actions, GitHub's automation service, the keys to reach the server live in the repository's secrets, under the path given in the GitHub documentation.
Note: simplified diagram of the GitHub screen, November 2026.
For production, one more step is worth it: an environment, a deployment target with its own rules. According to the documentation on environments, its secrets only reach the jobs that reference it, and with "required reviewers" a job can't see them until a named person approves it. On GitHub Free, environment secrets only work in public repositories; private ones need the Pro, Team or Enterprise plans.
Environment secrets
Note: simplified diagram of the GitHub screen, November 2026.
# .github/workflows/deploy.yml: the secret arrives as an environment variable of the step
jobs:
deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v7
- name: Deploy to the server
env:
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
run: ./deploy.sh
When there are many secrets: secrets managers
With more servers, people and environments you move to a secrets manager, a service that holds the keys and can change them automatically. Two common examples: AWS Secrets Manager, which according to the AWS documentation can rotate secrets automatically, and HashiCorp Vault, which for databases generates credentials on demand, different for each service and revoked when they expire. There are others, such as Doppler. For a small business with one site and one management system, variables on the server are often enough.
An honest note: the OWASP Secrets Management Cheat Sheet, a reference guide on application security, points out that environment variables are accessible to all processes and may end up in logs: better than a file in the repository, not the finish line.
Reading variables in PHP: getenv(), $_ENV and $_SERVER
In PHP the same value can come from three places, and this is where many "it works locally, not on the server" problems come from.
getenv('NAME')reads the process environment and returnsfalseif the variable doesn't exist (PHP manual).$_ENVis only filled if thevariables_ordersetting contains the letter E. The manual gives "EGPCS" as the default, but the php.ini-production shipped with PHP uses "GPCS": no E, so on many servers$_ENVis empty.$_SERVER: with PHP running as CGI or FastCGI, as with PHP-FPM, the manual warns that it also contains the environment values.
That's why a small function helps: it tries all three and, if the variable is missing, stops the program with a clear message instead of connecting with an empty password. It works on PHP 8.2 and later and never prints the value.
<?php
declare(strict_types=1);
/**
* Reads a required environment variable.
* If it's missing, the program stops with a clear message (never printing secret values).
*/
function env_required(string $name): string
{
$value = getenv($name); // the process environment
if ($value === false) {
$value = $_SERVER[$name] ?? $_ENV[$name] ?? null; // SetEnv, FastCGI, variables_order
}
if (!is_string($value) || trim($value) === '') {
throw new RuntimeException("Missing configuration: set the {$name} variable on the server.");
}
return $value;
}
$pdo = new PDO(
'mysql:host=' . env_required('DB_HOST') . ';dbname=' . env_required('DB_NAME') . ';charset=utf8mb4',
env_required('DB_USER'),
env_required('DB_PASSWORD'),
);
Rotating passwords and keys
Rotating a secret means replacing it with a new one and disabling the old one. That way a stolen key only works for a short time: that's the reason OWASP gives.
How often?
There is no single number that fits everything.
- OWASP asks for regular rotation and automation, without fixing an interval: from minutes to years, depending on what the key protects.
- NIST, the US standards body, in its SP 800-63B-4 guidelines (July 2025), forbids requiring people to change their password periodically, and requires a change when there is evidence it has been compromised.
- Providers tell you when: Stripe recommends replacing keys when someone who knew them leaves the company or changes role.
In practice: people's passwords get changed when there is a suspicion, and are protected with two-step login. Machine keys (database, API, server) get rotated every time people or suppliers change, after every suspicion, and on a fixed schedule you decide with your developer.
How to rotate without taking the site down
The trick is to have two valid keys at the same time for a while. Stripe supports it: when you rotate a key from the dashboard, the old and new keys both work for up to 7 days. MySQL 8.4 lets a user have two passwords at once (RETAIN CURRENT PASSWORD), precisely to change them without interruptions; where the hosting doesn't grant that permission, you create a second database user with the same rights.
- List where the key is used: site, management system, scheduled tasks, GitHub Actions.
- Create the new key without deleting the old one.
- Update the value where it lives: server variable, GitHub secret, hosting panel. Never in the code.
- Reload or redeploy whatever has to read the new value.
- Check: the site works, the logs show no access errors, the service no longer sees requests with the old key.
- Revoke the old one: expiry on Stripe,
DISCARD OLD PASSWORDon MySQL, deletion of the temporary user. - Write down the date, the reason and the next deadline.
If a key has already ended up on GitHub
Order matters. GitHub's guide on sensitive data says to revoke or rotate first: a key that no longer works does no harm, even if it stays in the history.
- Revoke and rotate right away every secret in the file, with the procedure above.
- Check the service logs (payments, cloud, email) for the period the key was exposed.
- Clean the history, if needed. GitHub points to git-filter-repo; a common alternative is BFG Repo-Cleaner, which needs Java and by default doesn't touch the latest commit.
- Tell everyone who has a copy: they all have to clone the repository again.
# Removes .env from the whole history (git-filter-repo 2.47 or later), then rewrites GitHub
git-filter-repo --sensitive-data-removal --invert-paths --path .env
git push --force --mirror origin
Why isn't the cleanup enough on its own? GitHub says so itself: the data stays in other people's copies and in forks, and cached views and pull requests can still show it (for those you need GitHub Support). Rewriting the history takes the key out of the shop window, not out of the hands of whoever already copied it.
GitHub's defences: secret scanning and push protection
GitHub's secret scanning looks for keys across the whole history, on all branches. According to the documentation, on public repositories it's free and automatic; for organizations' private repositories it requires GitHub Secret Protection, on the Team or Enterprise plans. When it finds a key from a provider that partners with GitHub, it notifies that provider, who can revoke it.
Push protection blocks the push before the key reaches GitHub. For personal accounts it's on by default for public repositories (documentation); at repository level you turn it on from Settings, Advanced Security.
Push protection: blocks commits that contain secrets
Note: simplified diagram of the GitHub screen, November 2026.
If a push is blocked, GitHub offers a link to bypass it, with three reasons. Every bypass sends an alert to the people in charge: it shouldn't be used for real keys.
It's used in tests
It's a false positive
I'll fix it later
Note: simplified diagram of the GitHub screen, November 2026.
Checklist: what, where, how often
| What | Where it lives | How often to check or rotate |
|---|---|---|
.env and secrets files | Outside the repository and outside the public folder | Check at every new project and every handover |
.env.example | In the repository, with no values | At every new variable |
| Database password | Server variable or file outside the public folder | At every change of people or suppliers, after a suspicion, on a fixed schedule |
| API keys (payments, AI, email) | Server variables, hosting panel or secrets manager | As above; immediately if they show up in chat, email or code |
| Deployment keys (SSH, FTP) | GitHub Actions secrets, preferably in an environment | At every change of people; immediate revocation if exposed |
| Personal passwords for panels and accounts | Password manager, with two-step login | Only when there's a suspicion (NIST SP 800-63B-4) |
| Secret scanning and push protection | Repository settings on GitHub | Always on; alerts read every week |
From my experience
I've been a developer since 2003 and a freelancer since 2008: keys are the part of a project you see least and that weighs most. In an ecommerce I worked on from 2018 to 2023, orders and stock went through Amazon Seller Central and eBay via their APIs: keys that move real orders. In CuraPiù, the software for care homes that I designed, each facility has its own database, login takes two steps and a log records who did what: I tell the story in the CuraPiù case study. And when I take over a project, changing passwords and keys is among the first steps, as I explain in the guide on what to do if your web developer disappeared: not out of distrust, it's basic hygiene.
Frequently asked questions
Can the .env file go in a private repository?
No. A private repository gets cloned, copied into backups and connected to other services, and GitGuardian finds that internal repositories contain secrets about six times more often than public ones. Only a .env.example with no values goes in the repository; the real values live on the server or in GitHub secrets.
I deleted the .env from GitHub: am I safe?
No. Git history keeps every version, so the file can be read again by going back through the commits, and anyone who already copied it still has it. The first thing to do is revoke and rotate every key in the file; only then does cleaning the history with git-filter-repo or BFG make sense.
How often should passwords be changed?
It depends on who uses them. People's passwords get changed when there's a suspicion of compromise, as NIST states in its SP 800-63B-4 guidelines. Machine keys, such as database and API keys, get rotated at every change of people or suppliers, after every suspicion and on a fixed schedule agreed with your developer.
What should I ask my developer?
Four things: a list of the project's secrets and where they're stored, confirmation that the repository doesn't contain a .env, not even in its history, push protection turned on in GitHub, and a written rotation procedure. If an answer is vague, it's time for a check.
Where to start
If you don't know where your site's passwords are and who knows them, the first step is an inventory. It's what I do when I take over the code of a project: I recover access and the repository, check the history, move the secrets to the server, rotate them and hand everything over in your name, with the written list. For AI service keys, read how to integrate ChatGPT or Claude into business software. Book the free 30-minute analysis: we'll look at your project together and decide where to begin.