Laravel Environment Secrets on Servers

Published 2026-11-29 · Updated 2026-11-29 · 9 min read · Sora Panel team

A Laravel server needs credentials to reach databases, mail providers and other services, but putting every value into a shared deployment script or a Git repository makes ownership and rotation difficult. Start with an inventory of what is sensitive, who and what needs it, and how to replace it. Then protect the application files, delivery path, running processes and backups as parts of the same system.

Illustration: protected application secrets and controlled access
Illustration, not a product screenshot.

Classify settings and map their consumers

Not every configuration value is a secret. An application URL or feature flag may be operationally sensitive but does not necessarily grant access; a database password, private key, API token or Laravel application encryption key does. Classify by consequence if disclosed or changed, rather than by whether a value happens to be stored in an environment file. Record each credential's owner, issuing service, scope, environments, consumers, rotation method and emergency contact without recording the value itself in the inventory.

The Laravel configuration documentation describes the distinction between an example environment file with placeholders and an actual .env containing environment-specific settings. Keep the real file out of source control. Treat staging credentials separately from production and avoid copying production secrets into developer machines or test data. External environment variables can override values from the file, so identify the source that actually wins before troubleshooting a mismatch.

CategoryExampleHandling decision
Public configurationApplication URLReview changes; a secret store is not necessarily required
Service credentialDatabase or mail passwordLimit scope, rotate and revoke at the provider
Encryption keyLaravel APP_KEYPlan compatibility with existing encrypted data before rotation
Recovery materialBackup decryption keySeparate protected storage and tested recovery access

The OWASP secrets management guidance recommends least privilege, lifecycle management and auditable access. Apply those principles to people as well as processes: the web application, deployment identity, queue workers and backup system should not automatically share the same broad access. Give an accountable owner responsibility for reviewing access after staff or roles change.

Protect the server and delivery path

Serve the application's public directory rather than its project root. Laravel's deployment guide warns that serving the project root can expose sensitive configuration files. Check the actual web-server document root for each virtual host, including alternate hostnames and staging sites. Restrict access to environment files, configuration caches, logs and backup archives through operating-system permissions and service isolation; do not rely solely on a hidden filename.

Use a controlled secret manager or another documented delivery process appropriate to the environment. Prefer scoped, short-lived credentials where the issuing service supports them. If a deployment writes a file, ensure only the intended application identity and necessary administrators can read it, and that other sites on the host cannot. Avoid passing secret values in command-line arguments, tickets or chat. Protect shell history, process listings, CI logs, artifacts and deployment traces from inadvertent exposure.

Encrypt backups containing configuration or application data, restrict backup access independently, and test restoration with the keys and permissions actually available to the recovery team. A protected production file is not enough if old releases or unprotected snapshots contain copies. Plan for what happens when the secret store or identity provider is unavailable: emergency access must itself be protected, auditable and periodically exercised.

For encrypted environment files, Laravel provides built-in encryption and decryption commands. The decryption key remains a separate secret and must be delivered through a different protected channel; encrypted files do not make a leaked decryption key harmless. Avoid printing keys in automated logs, and review the overwrite behavior of decryption commands before using them against an existing production file. A placeholder in an example file must never be a real credential.

Understand configuration caching and workers

Laravel can cache configuration during deployment. Once cached, the framework does not load the .env file during requests or Artisan commands; env() outside configuration files will then see only external system-level environment variables. Put environment lookups in configuration files and use Laravel's configuration accessors in application code. Treat the resulting cached configuration as sensitive because it can contain resolved secret values.

Changing a secret source does not guarantee that every consumer uses it immediately. Build the intended configuration cache using the correct environment and release, then refresh long-lived consumers according to their documented lifecycle. Laravel's queue guide explains that workers keep their booted application in memory and need a restart to load changes. Coordinate that restart with active jobs and the process manager; see the worker deployment guide.

Verify the change by exercising a narrowly scoped operation and checking its result, not by printing a configuration dump. A successful web request is insufficient if a separate scheduler or worker still holds an old credential. Inspect each consumer's identity, effective environment source, release and restart status without exposing the secret itself. If a deployment fails, avoid reverting to an already revoked credential just to make a health check pass.

Rotate by credential type

For a routine service credential, inventory every consumer first. Where the provider supports overlapping credentials, create a narrowly scoped replacement, deliver it to each consumer, refresh cached configuration and long-running processes, then verify the intended operation. Revoke the old credential after all intended consumers have moved and record the result. If overlap is unavailable, arrange a coordinated cutover and an explicit recovery plan. A rotation is not complete while an old credential remains valid unnecessarily.

Compromise changes the priority: contain and revoke promptly using the issuing provider's controls, and coordinate availability impact with the incident owner. Preserve useful evidence without copying the secret into new systems. Identify access and activity during the exposure window and review dependent credentials where appropriate. OWASP notes that restarting an application does not itself revoke a stolen credential; only the issuer's expiry or revocation controls do that.

Do not treat APP_KEY like an ordinary API token. It protects application-encrypted material and may affect existing sessions and cookies. Before changing it, inventory what your application encrypts and consult the Laravel encryption documentation for key rotation and previous-key support. Plan data compatibility, secure retention of any previous keys required for decryption, and a tested recovery path. Blindly generating a new key on a live application can make existing encrypted data unavailable.

After every planned rotation, document the issuing service, affected environments, consumer validation, revocation confirmation and accountable owner. Record identifiers and timestamps, not secret values. Review how the old value might remain in configuration caches, old releases, process memory or encrypted backups, and handle retention under your security and recovery policy.

Scan for leaks, then respond to findings

Secret scanning can catch recognizable credentials in code and history, but it is a detection layer rather than a guarantee. Choose tools according to the repositories, formats, deployment workflow, policy and support you can operate. Scan pull requests and historical content where appropriate, protect scanner output, and assign ownership for triage. A finding may be a real active key, a revoked key, a test fixture or a false positive; treat uncertainty as a reason to investigate rather than publish the candidate value.

The following snapshot shows GitHub stars for three public scanner repositories, not their detection accuracy, security, coverage or suitability. The projects have different histories and users. Review their documentation and test them against a controlled set of synthetic fixtures before adopting one.

Open-source secret scanners: GitHub stars

Public repository snapshot; not a scanner quality test

  • gitleaks/gitleaks
    31,420
  • trufflesecurity/trufflehog
    29,790
  • Yelp/detect-secrets
    4,683
Stars indicate repository attention, not detection coverage or security. All three repository API snapshots are linked in the article; counts change over time. Source: GitHub repository APIs, 29 November 2026, viewed 2026-11-29.
View chart data
ItemstarsNote
gitleaks/gitleaks31,420
trufflesecurity/trufflehog29,790
Yelp/detect-secrets4,683

The repository API snapshots were viewed on 29 November 2026: Gitleaks, TruffleHog and detect-secrets. Counts can change and should not be used as a ranking of scanner effectiveness.

GitHub's remediation guidance says a committed secret should be considered compromised. Identify the issuer and affected services, revoke or rotate it, update dependent consumers, and examine relevant provider logs. Removing the value from the current file or rewriting Git history does not revoke a copied credential. History cleanup may be useful after containment, but it must not delay revocation.

Make the process repeatable

Maintain an inventory and a rotation runbook per service, including the identities authorized to request changes and the person who can approve an emergency action. Rehearse the process on a non-production credential: issue a replacement, deliver it without displaying it, reload each consumer, confirm access, revoke the old value and prove that it no longer works through an approved test. Test restore access separately from day-to-day deployment access.

Use production-safe observability: record the secret identifier or version and the consumer's success status, not its contents. Alert on failed authentication or unexpected access while preventing logs from becoming a second secret store. Review scanners and their exceptions periodically; a silenced finding should have an owner and justification. Remove unused credentials instead of rotating them indefinitely.

Finally, rehearse the uncomfortable case where the host itself is compromised. Rotating a key while an attacker still controls the host may simply expose its replacement. Isolate and investigate the environment, restore trusted access and coordinate replacement of affected credentials according to the incident plan. See also scheduler operations for another consumer of application configuration. Sora Panel is not released yet. Read how it works on the homepage.

Frequently asked questions

Is putting .env in .gitignore sufficient?

No. Protect server permissions, backups, deployment logs, cached configuration and every other copy, and rotate any secret already committed.

Does changing .env immediately update workers?

Not necessarily. Rebuild the intended configuration cache and restart long-lived workers according to a tested deployment procedure.

Should I regenerate APP_KEY after every deployment?

No. It can protect existing encrypted data; use a deliberate key-rotation and recovery plan.

Does deleting a leaked secret from Git revoke it?

No. Revoke or rotate it at the issuing provider, update consumers and investigate the exposure.

Sources

Sora Panel is not released yet. Read how it works on the homepage.