Secrets Management for WordPress: Protecting Your Database Credentials and API Keys

Secrets Management for WordPress: Protecting Your Database Credentials and API Keys

What Secrets Does WordPress Store?

WordPress applications handle multiple categories of sensitive information that must be protected from unauthorized access. Understanding what secrets your site manages is the first step toward implementing proper security controls.

Database Credentials

Your wp-config.php file contains four database connection constants:

  • DB_NAME: Your WordPress database name
  • DB_USER: MySQL username with database access
  • DB_PASSWORD: MySQL password (the most critical secret)
  • DB_HOST: Database server address (often “localhost” but may be remote)

These credentials give direct access to all WordPress data—posts, users, comments, and transactional information. A compromised database password allows attackers to steal, modify, or delete entire databases.

Authentication Keys and Salts

WordPress uses six cryptographic constants to secure user sessions and forms:

  • AUTH_KEY & AUTH_SALT: Encrypt authentication cookies for standard logins
  • SECURE_AUTH_KEY & SECURE_AUTH_SALT: Protect admin panel logins over HTTPS
  • LOGGED_IN_KEY & LOGGED_IN_SALT: Secure logged-in user session cookies from hijacking
  • NONCE_KEY & NONCE_SALT: Generate one-time tokens for forms, preventing CSRF attacks

As documented by WordPress.org, these values are random strings designed to be changed regularly. Changing them invalidates all existing user sessions—a critical operation after security incidents.

Third-Party API Keys and Payment Gateway Credentials

Modern WordPress sites integrate with external services:

  • Stripe, Square, or PayPal payment keys (PCI-DSS sensitive)
  • Email service providers (SendGrid, Mailgun, AWS SES SMTP credentials)
  • Cloud storage API keys (AWS S3, Google Cloud, Azure Blob)
  • Analytics and monitoring tokens (New Relic, Datadog, Bugsnag)
  • CDN or caching service credentials (Cloudflare, Bunny CDN)
  • Social media app keys (OAuth tokens, consumer keys/secrets)

Each integration adds another credential that must be protected. Exposed API keys allow attackers to impersonate your application, charge fraudulent transactions, or access private customer data.

The Risks of Hardcoding and Committing Secrets

Hardcoding secrets directly in source code—especially in version-controlled files—creates multiple attack vectors that compound over time.

Why Hardcoded Credentials Are Catastrophic

According to OWASP, hardcoded passwords have several critical drawbacks:

  • All developers see the secret: Every team member with repository access can view production credentials, multiplying exposure risk across your organization.
  • Impossible to rotate without redeployment: Changing a hardcoded password requires code changes, testing, and full application redeployment—a process that can take hours or days.
  • Permanent history in git: Deleting a secret from the current commit doesn’t erase it from git history. Tools like git log and git show reveal every version of that file, including credentials.
  • Public repository exposure: One accidental public repository push exposes credentials to the entire internet. Automated bots scan GitHub for these patterns continuously.
  • Difficulty revoking access: Once compromised, hardcoded credentials remain valid in production until manually changed, often requiring coordination across teams.

The GitHub Leak Crisis

Real-world data from Snyk’s 2026 research shows that 28 million credentials leaked on GitHub in 2025 alone. The leak rate continues accelerating as developers unknowingly commit secrets to public repositories. According to OWASP’s Secrets Management Cheat Sheet, hardcoded API keys and leaked environment variables are among the most common causes of data breaches affecting organizations of all sizes.

Vilee LLC combines deep technical expertise in WordPress/WooCommerce development with AI-powered automation to operate 520+ profitable online businesses at scale.

WordPress Secrets Management Best Practices

Protecting secrets requires a multi-layered approach combining technical controls, process discipline, and automation.

1. Use Environment Variables Instead of wp-config Hardcoding

Environment variables decouple secrets from source code. Load them at runtime from your server or deployment platform. In wp-config.php, retrieve values using:

  • getenv('DB_PASSWORD') — reads server-level environment variables
  • $_ENV['API_KEY'] — accesses PHP environment variables
  • $_SERVER['SECRET_VALUE'] — for certain web server configurations

Example secure approach:

define('DB_PASSWORD', getenv('DB_PASSWORD') ?: 'fallback_never_reaches_production');

This pattern loads from environment first, never storing production secrets in code.

2. Implement .env Files Outside the Web Root

Create a .env file containing environment variable definitions, positioned outside your publicly accessible directory:

  • Location: One directory above wp-content, inaccessible via HTTP
  • Permissions: 640 or more restrictive (readable by application user only)
  • Git exclusion: Add .env to .gitignore immediately—never commit this file
  • Format: Simple KEY=VALUE pairs, one per line

Libraries like vlucas/phpdotenv automate loading:

$dotenv = DotenvDotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();

3. Harden wp-config.php File Permissions

Even with environment variables, wp-config.php may contain sensitive values. Apply strict permissions:

  • File permissions: 640 (owner reads/writes, group reads, others have no access)
  • Ownership: Dedicated application user, not www-data if possible
  • Directory permissions: 750 on the WordPress root directory
  • Web access block: Deny HTTP requests to wp-config.php via server config

Example nginx configuration:

location ~ /wp-config.php$ { deny all; }

4. Never Commit wp-config.php or .env to Git

Git stores every version of every file permanently. A secret committed and later deleted remains in history. Best practices:

  • Add wp-config.php, .env, and .env.local to .gitignore
  • Commit a .env.example template showing required variables without values
  • Document setup instructions for new developers referencing the example file
  • Use pre-commit hooks with Gitleaks to block commits containing secret patterns

5. Implement Least Privilege Access Control

According to OWASP, “Engineers should not have access to all secrets in the secrets management system.” Apply principle of least privilege:

  • Database users: Create separate MySQL accounts for different application components (e.g., read-only for reports, full for transactions)
  • API credentials: Scope permissions to specific resources and operations (e.g., Stripe key restricted to charges, not customer deletion)
  • SSH/deployment credentials: Limit to authorized deployment systems only
  • Team access: Not all developers need production secrets; staging/development use separate credentials

6. Maintain Separate Secrets Across Environments

Never reuse production credentials in development. Maintain distinct secrets for:

  • Local development: Dummy data and test API keys, stored in local .env
  • Staging: Separate test credentials matching production format but non-destructive
  • Production: Real credentials, rotated regularly, audited strictly

This containment strategy prevents developers from accidentally using production data during testing.

Advanced: Secrets Management Tools and Vaults

As teams scale, manual .env file management becomes error-prone. Dedicated secrets management platforms provide encryption, rotation, auditing, and team collaboration.

HashiCorp Vault for WordPress

HashiCorp Vault is an enterprise-grade secrets manager offering dynamic credential generation, automated rotation, and comprehensive auditing. Human Made provides a WordPress plugin that integrates Vault with WordPress:

  • Dynamic credentials: Generate temporary database passwords that expire after use
  • Automatic rotation: Vault rotates credentials on a schedule; WordPress automatically fetches renewed values
  • Lease management: When leases expire, Vault revokes old credentials, preventing reuse attacks
  • Caching via transients: WordPress transients API caches secrets to reduce external API calls
  • Audit logging: Every secret access is logged for compliance and breach investigation

Implementation pattern: WordPress fetches secrets from Vault via HTTP API, caches them briefly, and rotates them automatically via wp-cron hooks.

AWS Secrets Manager

As documented by RayHeffer.com, AWS Secrets Manager integrates with wp-config.php to manage sensitive configuration. Benefits include:

  • Encryption at rest using AWS KMS
  • Automatic secret rotation configured on a schedule
  • Fine-grained IAM policies controlling who can access which secrets
  • Integration with AWS CloudTrail for audit logging
  • Seamless rotation without application redeployment

CI/CD Pipeline Secrets

GitHub Actions, GitLab CI, and other CI/CD systems offer built-in secrets storage:

  • GitHub Actions: Store secrets in repository or organization settings; reference as ${{ secrets.SECRET_NAME }}
  • GitLab CI: Define protected variables accessible only to authorized pipelines
  • Jenkins: Use credentials plugins to store and inject secrets during builds
  • Best practice: Never echo secrets to build logs; mask them in output

Secret Rotation and Lifecycle Management

Secrets have lifecycles: creation, deployment, rotation, and revocation. Proper lifecycle management limits exposure window if credentials are compromised.

Database Password Rotation

Implement routine password rotation following these steps:

  1. Generate a new secure password using a password manager or openssl rand -base64 32
  2. Update the MySQL account with ALTER USER 'username'@'localhost' IDENTIFIED BY 'new_password';
  3. Update the secret in your secrets manager or environment variable
  4. Verify WordPress connectivity after deployment
  5. Document the rotation in your audit log
  6. Schedule rotation quarterly or after security incidents

API Key Rotation

Most SaaS providers support multiple active API keys, enabling safe rotation:

  • Create new key: Generate a new key in the service’s dashboard
  • Test with new key: Update staging environment and verify functionality
  • Deploy new key: Update production secrets manager with the new key
  • Verify in production: Monitor for successful API calls with new key
  • Revoke old key: Disable the old key after 24-48 hours of successful operation

WordPress Salts and Keys Rotation

Changing AUTH_KEY, SECURE_AUTH_KEY, LOGGED_IN_KEY, and NONCE_KEY forces all users to log in again (resetting cookies). RandomKeygen.com provides a generator. Rotate in these scenarios:

  • Suspected admin account compromise
  • After a security plugin detected malware
  • Quarterly as preventive measure
  • When transferring a site to new hosting

Note: Rotating salts should be communicated to users since they’ll be logged out.

Detecting and Responding to Leaked Secrets

Despite best efforts, secrets may leak. Rapid detection and response are critical to limiting damage.

Pre-Commit Scanning Tools

Catch secrets before they reach git with client-side hooks. Top tools include:

  • Gitleaks: Pattern-based detection for AWS keys, Stripe tokens, SSH keys. Run as pre-commit hook.
  • TruffleHog: Uses entropy detection (high-randomness strings) plus pattern matching; can verify if leaked credentials are actually valid.
  • detect-secrets: Yelp’s tool supporting ~20 secret types; generates baseline files to avoid alert fatigue.
  • ggshield: GitGuardian’s tool with real-time scanning of commits and push attempts.

Example pre-commit integration:

#!/bin/bash
gitleaks detect --verbose --source git
if [ $? -ne 0 ]; then exit 1; fi

Full Repository Scanning

Scan entire git history for existing leaks:

gitleaks detect --source git --verbose --report-path leaks.json

This discovers secrets in branches, deleted commits, and tags. According to GitGuardian’s 2026 report, dedicated secret scanning tools scan the full git history—not just the current commit—catching leaks from months ago.

Incident Response Protocol

If a secret leaks, follow this procedure immediately:

  1. Revoke: Disable the compromised credential (delete API key, reset password)
  2. Replace: Generate and deploy a new secret using your secrets manager
  3. Remove from history: Use git-filter-branch or BFG Repo Cleaner to permanently delete the secret from git history (requires force-push and team coordination)
  4. Scan logs: Check server logs, database logs, and monitoring systems for unauthorized access using the old credential
  5. Notify stakeholders: Inform security team, users affected by the compromised data, and relevant compliance officers
  6. Post-mortem: Document how the leak occurred and implement controls to prevent recurrence

Implementation Checklist

Task Frequency Owner Status
Audit all hardcoded secrets in wp-config.php One-time DevSecOps
Migrate secrets to environment variables One-time Lead Developer
Create .env.example template without values One-time Lead Developer
Add .env and wp-config.php to .gitignore One-time DevOps
Set file permissions (640 on wp-config, 750 on root) One-time DevOps
Implement pre-commit Gitleaks hook One-time DevSecOps
Run full repository secret scan (TruffleHog) One-time Security Team
Deploy secrets manager (Vault, AWS Secrets Manager) One-time DevOps
Rotate database password Quarterly DBA
Rotate API keys and tokens Semi-annually DevOps
Rotate WordPress salts and keys Quarterly Lead Developer
Review secret access logs (audit trail) Monthly Security Team
Update team documentation on secret management Annually Tech Lead
Conduct secrets management training Annually Security Team

Common Mistakes and How to Avoid Them

  • Committing .env files: Remove from git history and update .gitignore. Use git rm --cached .env to stop tracking.
  • Using same secrets across environments: Maintain separate credentials for dev, staging, and production to prevent test code from touching real data.
  • Forgetting to mask secrets in logs: Configure your logging system to redact API keys and passwords in debug output.
  • Rotating secrets manually: Automate rotation via your secrets manager to reduce human error and downtime.
  • Not scanning existing repositories: Legacy projects often contain committed secrets. Scan full history with TruffleHog today.

Integration with Your WordPress CI/CD Pipeline

Incorporate secrets management into your deployment workflow:

  • During CI/CD builds, inject secrets as environment variables from your secrets manager
  • Run Gitleaks in your pre-push hooks and CI pipeline to block leaks
  • Use deployment tools that support secrets injection (GitHub Actions, GitLab CI, Jenkins)
  • Never log or echo secrets in build output; mask sensitive values
  • Test deployment with non-production secrets in staging before using real credentials

Conclusion

WordPress secrets management is not optional—it’s foundational to site security. By moving secrets out of code, implementing environment variables, rotating credentials regularly, and detecting leaks early, you prevent the majority of WordPress security breaches. Start with the checklist above: audit existing secrets, implement .env files, add pre-commit scanning, and commit to regular rotation.

For managed WordPress security implementation, contact our team. We automate secrets management across your entire WordPress infrastructure, eliminating manual work and human error.

Frequently Asked Questions

Frequently Asked Questions

Can I keep wp-config.php in version control if I exclude secrets?

No—many developers accidentally commit wp-config.php before moving to environment variables. Best practice is to exclude it entirely via .gitignore, commit a .env.example template instead, and document setup instructions. This prevents accidental commits of sensitive data.

What should I do if I find a database password in my git history?

Immediately: (1) Revoke/reset the MySQL password in your database, (2) deploy a new password to your secrets manager, (3) use BFG Repo Cleaner or git-filter-branch to permanently remove it from all commits, (4) force-push to all remotes after cleaning, (5) scan logs for unauthorized access using the old password.

How often should I rotate WordPress salts?

Quarterly at minimum, immediately after suspected admin compromise or malware detection. Rotation forces all users to log in again (resetting their session cookies), which is disruptive, so schedule rotations during low-traffic periods and communicate the change to users in advance.

Talk to us →