To keep secrets out of wp-config.php and out of version control, load them from a .env file with the vlucas/phpdotenv library and read them through a tiny helper. The whole pattern is this: install phpdotenv with Composer, load the .env near the top of wp-config.php, then feed the values into the define() calls WordPress already expects.
require_once __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable( __DIR__ );
$dotenv->load();
function te_env( $key, $default = null ) {
$value = $_ENV[ $key ] ?? getenv( $key );
return false === $value || null === $value ? $default : $value;
}
define( 'DB_NAME', te_env( 'DB_NAME' ) );
define( 'DB_USER', te_env( 'DB_USER' ) );
define( 'DB_PASSWORD', te_env( 'DB_PASSWORD' ) );
define( 'DB_HOST', te_env( 'DB_HOST', 'localhost' ) );With createImmutable( __DIR__ ) as above, the .env sits next to wp-config.php. Moving it one level up, outside the web root, is better; then the call becomes createImmutable( dirname( __DIR__ ) ), as in the template further down. Either way, the file holds the actual values:
DB_NAME=production_db
DB_USER=wp_app
DB_PASSWORD=the-real-password-here
DB_HOST=127.0.0.1
WP_HOME=https://yoursite.comThat is the technique. The rest of this article is the parts that matter once you ship it: where to install phpdotenv, how createImmutable() behaves, the three security must-dos that turn this from "nice idea" into "did not just leak your database password to the internet", a Composer-autoloaded must-use plugin for plugin-level secrets, and a hardened wp-config.php template for everything that stays in the file.
Why move secrets out of wp-config.php at all
The default WordPress setup hardcodes everything in wp-config.php: database credentials, the salts, and over time every plugin's API key (define( 'SENDGRID_API_KEY', '...' ), a Stripe secret, an S3 access key). That file then sits in the same directory tree as your code. The moment wp-config.php is tracked in git, or copied into a backup that ends up somewhere readable, or differs per environment and someone commits the wrong copy, the secret is out.
The Twelve-Factor App "Config" guidance is the cleanest statement of the principle: strict separation of config from code, with anything that varies between deploys (and anything secret) held in the environment, not in a file you commit. A .env file is the local, file-backed version of that environment. The same wp-config.php ships everywhere; only the .env differs, and the .env never enters version control.
When does the traditional all-in-wp-config.php approach still make sense? On a single hand-managed site that you never deploy from git, where wp-config.php already lives outside any repository, the env file buys you little. The pattern earns its keep the moment you have more than one environment (local, staging, production), a deploy pipeline that pulls code from git, or secrets that a teammate should never see in plaintext in the repo.
Installing phpdotenv with Composer
phpdotenv is a Composer package. From the directory that holds (or will hold) your composer.json:
composer require vlucas/phpdotenvThat writes the library into vendor/ and an autoloader at vendor/autoload.php. Everything downstream depends on that autoloader being required before you call Dotenv\Dotenv.
Where you put the Composer project depends on how your install is laid out:
- Composer-managed WordPress (Bedrock-style or a custom layout): you already have a root
composer.jsonabove the web root. phpdotenv installs into the existingvendor/, and the autoload is already wired up. - A traditional install you do not want to "Composerize": run
composer requirein the WordPress root (or a directory beside it) purely to vendor the one library, thenrequire_onceits autoloader fromwp-config.php.
Loading it from wp-config.php vs an MU-plugin
There are two places the load can happen, and the right one depends on what you are reading.
Database credentials and salts must load in wp-config.php, because WordPress reads DB_NAME and friends before any plugin runs. The autoload + Dotenv::createImmutable() + define() block goes near the top of wp-config.php, above the require_once ABSPATH . 'wp-settings.php'; line.
Plugin API keys and other non-core secrets (an SMTP key, a payment-gateway secret) do not need to exist that early. For those, a must-use plugin is the tidier home: it loads automatically, survives theme switches, and keeps the secret-reading code out of the database. If you autoload Composer dependencies from an MU-plugin already, that is the natural spot. I walk through that wiring in loading Composer packages from a must-use plugin below. If the .env is already loaded in wp-config.php, the values are in $_ENV by the time the MU-plugin runs, so the plugin just reads them with the same te_env() helper and does not load the .env a second time.
Reading values and feeding the constants
Dotenv\Dotenv::createImmutable( __DIR__ ) builds a loader pointed at the directory holding the .env, and load() parses it. "Immutable" means it will not overwrite a variable that is already set in the real environment, so a value exported by your server or container (a true environment variable) wins over the file. That is usually what you want: the .env is the local default, and the platform's real env vars override it in production if you set them there. If you genuinely need the file to clobber existing env vars, createMutable() exists, but reach for it deliberately.
After load(), every KEY=value line is available in $_ENV['KEY'] and $_SERVER['KEY']. Not in getenv('KEY'): since phpdotenv 5, createImmutable() no longer calls putenv(), so getenv() only sees variables the server or container really exported (use createUnsafeImmutable() if a library insists on getenv()). I wrap the read in one small helper so the access pattern (and the default-value handling) lives in exactly one place:
function te_env( $key, $default = null ) {
$value = $_ENV[ $key ] ?? getenv( $key );
if ( false === $value || null === $value ) {
return $default;
}
return $value;
}Then feed those into the define() calls WordPress expects. The constant names are fixed by core (DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, the salts, WP_DEBUG), so they stay exactly as WordPress names them, the helper just supplies the value:
define( 'DB_NAME', te_env( 'DB_NAME' ) );
define( 'DB_USER', te_env( 'DB_USER' ) );
define( 'DB_PASSWORD', te_env( 'DB_PASSWORD' ) );
define( 'DB_HOST', te_env( 'DB_HOST', 'localhost' ) );
define( 'AUTH_KEY', te_env( 'AUTH_KEY' ) );
define( 'SECURE_AUTH_KEY', te_env( 'SECURE_AUTH_KEY' ) );
// ... and the rest of the salts.
define( 'WP_DEBUG', filter_var( te_env( 'WP_DEBUG', 'false' ), FILTER_VALIDATE_BOOLEAN ) );Two details worth flagging. First, everything in a .env is a string, so WP_DEBUG=false reads back as the string "false", which is truthy in PHP. Run boolean-ish values through filter_var( ..., FILTER_VALIDATE_BOOLEAN ) so false, 0, and off all resolve correctly. Second, for plugin secrets you do not have to define() a constant at all, you can read te_env( 'SENDGRID_API_KEY' ) directly wherever the value is used. Constants make sense when WordPress or a plugin specifically looks one up; otherwise the direct read is fine. (If you are wiring up transactional mail, sending WordPress email through SendGrid is a good example of a key that belongs in .env, not in the plugin's settings table.)
A .env for a fuller setup looks like this:
DB_NAME=production_db
DB_USER=wp_app
DB_PASSWORD=the-real-password-here
DB_HOST=127.0.0.1
AUTH_KEY=put-a-unique-salt-here
SECURE_AUTH_KEY=another-unique-salt
# ... the rest of the eight salts
WP_DEBUG=false
SENDGRID_API_KEY=SG.real-key-valueThe security must-dos (do not skip these)
The env-file pattern only improves your security posture if you get these three right. Get them wrong and you have moved the secret from a file that was at least usually outside git into a file that is sitting in your web root and committed to the repo, which is strictly worse.
1. Add .env to .gitignore, always
The entire point is keeping secrets out of version control. Add the file to .gitignore before you ever write a real value into it:
.env
.env.*
!.env.exampleThat ignores .env and any .env.local / .env.production variants, while explicitly un-ignoring .env.example (covered below). If you have already committed a real .env once, the secret is in your git history even after you delete the file, so rotate those credentials, do not just git rm the file and assume you are clean.
2. Keep .env out of the web root, or block HTTP access to it
A .env sitting in the document root is one misconfigured server away from being served as plaintext. Anyone who requests https://yoursite.com/.env and gets a 200 back has your database password, your salts, and every API key in one response. This is a routine target for automated scanners. Treat it the same way you would the default head output you strip from a site: a file the server should never hand to a visitor.
Two ways to be safe, in order of preference:
- Best: put
.envone level above the web root. If WordPress lives in/var/www/site/public/, put the.envin/var/www/site/and pointDotenv::createImmutable( dirname( __DIR__ ) )(or an explicit path) at it. A file outside the document root cannot be requested over HTTP at all. - If it must stay in the web root, block it at the server. On Apache add a rule to
.htaccessthat denies the file, and on nginx add alocationblock that returns 404 for it:
<Files ".env">
Require all denied
</Files>location ~ /\.env {
deny all;
return 404;
}Do not rely on the server config alone if you can avoid it. The above-the-web-root placement is the one that holds up when someone later swaps Apache for nginx and forgets to port the rule.
3. Commit a .env.example with blank values
Because the real .env is git-ignored, a fresh clone has no idea which keys it needs. Commit a .env.example (which is tracked) listing every key with empty or dummy values:
DB_NAME=
DB_USER=
DB_PASSWORD=
DB_HOST=localhost
AUTH_KEY=
SECURE_AUTH_KEY=
# ... the rest of the salts
WP_DEBUG=false
SENDGRID_API_KEY=Setup on a new machine becomes cp .env.example .env and fill in the blanks. It documents the required config, it never contains a secret, and it is the file the !.env.example line in .gitignore deliberately keeps tracked.
.env vs wp-config constants: when to use which
These are not mutually exclusive, and the right call depends on the site.
| Concern | .env + phpdotenv | Constants hardcoded in wp-config.php |
|---|---|---|
| Secrets in git | Kept out (file ignored) | In the repo if wp-config.php is committed |
| Per-environment config | One codebase, many .env files | Edit the file or maintain copies per environment |
| Multi-environment deploys | Built for it | Painful, error-prone |
| Single hand-managed site, no git | Extra moving part | Perfectly fine, simpler |
| Reading config | Through te_env() / $_ENV | Direct constant reference |
| Dependency | Needs Composer + phpdotenv | None |
Use the env file when secrets must stay out of version control, when config varies per environment, or when a deploy pipeline pulls code from git. Stick with plain wp-config.php constants on a single, hand-managed site that lives outside any repo, where the env file is just one more thing to install. The phpdotenv approach also pairs naturally with the kind of performance and ops work in optimizing a WooCommerce store, where staging and production routinely point at different databases and services.
Verify it works
After wiring it up, confirm three things:
- The site loads. If the database constants are reading correctly from
.env, WordPress connects. An "Error establishing a database connection" usually means a typo in a.envkey name or a stray quote in a value (phpdotenv does handle quoted values, but unbalanced quotes break parsing). - The
.envis not committed. Rungit statusandgit check-ignore .env. Ifgit check-ignore .envprints.env, it is correctly ignored. Ifgit statusshows it as a tracked or staged file, fix.gitignorebefore you commit anything. - The
.envis not reachable over HTTP. Requesthttps://yoursite.com/.envin a browser or withcurl -I https://yoursite.com/.env. A 403 or 404 is what you want. A 200 with your credentials in the body means the file is exposed, stop and fix the placement or server rule immediately, then rotate the leaked secrets.
Load Composer packages from a must-use plugin
When the secrets your code needs are plugin-level (an SMTP key, a payment secret) rather than database credentials, the code that reads them usually belongs in a must-use plugin, and a real plugin quickly wants Composer: phpdotenv, an HTTP client, its own namespaced classes. Must-use plugins make that awkward for three reasons, all stated in the must-use plugins documentation:
- Only top-level files load. WordPress "only looks for PHP files right inside the mu-plugins directory", never in subdirectories, so
mu-plugins/my-plugin/my-plugin.phpis invisible. - They load alphabetically, before regular plugins, which is why people use them: hooks registered here are in place before any normal plugin or the theme.
- No activation hooks. "Activation hooks are not executed in plugins added to the must-use plugins folder", so
register_activation_hook()never fires.
The fix is a one-file loader at the top level that requires a normal Composer package one directory down:
wp-content/mu-plugins/
├── te-loader.php ← the only file WordPress loads
└── te/
├── composer.json
├── src/
│ └── Plugin.php
└── vendor/
└── autoload.phpte/composer.json maps the namespace to src/ with PSR-4. The trailing \\ on the prefix is required; it stops TE\\ also matching something like TEFoo\\:
{
"name": "techearl/te-mu-plugin",
"type": "wordpress-muplugin",
"license": "GPL-2.0-or-later",
"require": {
"php": ">=7.4"
},
"autoload": {
"psr-4": {
"TE\\": "src/"
}
}
}Run composer install inside te/ (or composer dump-autoload if only the map changed). TE\Plugin then resolves to src/Plugin.php and TE\Admin\Settings to src/Admin/Settings.php.
The loader guards the require, because vendor/ is generated and a fresh clone or a deploy that skipped composer install would otherwise fatal every request, wp-admin included. Instead it shows administrators an actionable notice and lets the site keep serving:
<?php
/**
* Plugin Name: TE MU Loader
* Plugin URI: https://techearl.com/wordpress-env-file-config
* Description: Loads the Composer-autoloaded must-use plugin that lives in the te/ subdirectory.
* Version: 1.0.0
* Author: Ishan Karunaratne
* Author URI: https://techearl.com
* License: GPL-2.0-or-later
* Text Domain: te-mu
*/
namespace TE;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function te_missing_deps_notice() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
printf(
'<div class="notice notice-error"><p>%s</p></div>',
esc_html__( 'TE MU Loader: Composer dependencies are missing. Run "composer install" in wp-content/mu-plugins/te/.', 'te-mu' )
);
}
$te_autoload = __DIR__ . '/te/vendor/autoload.php';
if ( ! file_exists( $te_autoload ) ) {
add_action( 'admin_notices', __NAMESPACE__ . '\\te_missing_deps_notice' );
return;
}
require_once $te_autoload;
Plugin::boot();src/Plugin.php is an ordinary class, so the plugin can be unit-tested and split into more classes under TE\ without touching the loader. With no activation hook, one-time setup moves to init, gated by an option so it is a no-op after the first run:
<?php
namespace TE;
class Plugin {
public static function boot() {
add_action( 'init', array( new self(), 'on_init' ) );
}
public function on_init() {
if ( get_option( 'te_mu_setup_done' ) ) {
return;
}
// One-time setup: create a table, seed an option, flush rewrite rules
// after registering a post type, etc.
flush_rewrite_rules();
add_option( 'te_mu_setup_done', 1 );
}
}The same gate handles schema versions: store a te_mu_db_version option and run migrations on init only when it differs from the code's constant. If .env is already loaded in wp-config.php, the plugin's classes read values with te_env() and never load the file a second time.

To verify, open Plugins → Must-Use in wp-admin: the loader appears by its Plugin Name, with no activate or deactivate link. That proves the top-level file loaded; to prove the class booted, check that something it registers takes effect, or drop a temporary error_log() into Plugin::boot() with WP_DEBUG_LOG on. Listed but inert usually means composer install never ran (the notice says so) or the PSR-4 prefix does not match the namespace in src/Plugin.php.
Hardened wp-config.php template
Moving secrets into .env fixes where they live; the rest of wp-config.php decides how much damage a compromise can do. It is the first PHP file WordPress loads, before any plugin, theme or database connection, so anything set here applies to the whole site and no plugin can override it. The installer's defaults are minimal. This is the annotated template I drop into production sites, with the database credentials and salts read from .env through the same te_env() helper. I wrote the first version in early 2019 after cleanups kept hitting the same five preventable issues: file editing enabled in the admin, mixed-content HTTPS, default salts, debug output shown to visitors, and the default wp_ table prefix. Each is a one-line fix here.
The order matters: anything that affects constants or path resolution has to come before the require_once ABSPATH . 'wp-settings.php' line at the bottom.
<?php
/**
* The base configuration for WordPress.
*
* Hardened defaults applied:
* - File editing disabled in admin (no PHP write-back path through the UI)
* - Auto-updates enabled for core minor releases (security patches arrive on time)
* - HTTPS forced for admin and login (cookies never traverse HTTP)
* - Salts rotated (every existing session becomes invalid)
* - Debug logging on, debug display off (errors are logged but not shown to visitors)
* - Limited post revisions (database stays sane)
* - Empty trash quickly (deleted posts don't linger as recoverable history)
* - Custom $table_prefix (defeats SQL injection payloads that assume wp_)
* - Cron managed by system cron, not page loads (more reliable, more secure)
*
* Secrets (database credentials, salts) come from .env via te_env().
*
* For the bigger-picture hardening this fits into, see:
* https://techearl.com/wordpress-malware-removal
* https://techearl.com/wordpress-file-integrity-monitoring-server-side
*/
require_once __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable( dirname( __DIR__ ) ); // .env one level above the web root
$dotenv->load();
function te_env( $key, $default = null ) {
$value = $_ENV[ $key ] ?? getenv( $key );
return false === $value || null === $value ? $default : $value;
}
// ============================================================
// Database settings
// ============================================================
/**
* Database name, user, password, host.
*
* The user should have ONLY the privileges WordPress needs on THIS database:
* GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER,
* CREATE TEMPORARY TABLES, LOCK TABLES, REFERENCES
* ON `your_db_name`.* TO 'your_db_user'@'localhost';
*
* Do NOT grant ALL ON *.* or the global FILE, PROCESS, SUPER or RELOAD privileges.
* A SQL injection with FILE can read /etc/passwd; with PROCESS it can see other
* tenants; with SUPER it can persist beyond WordPress entirely. Even ALL ON
* your_db_name.* adds TRIGGER, EVENT and CREATE ROUTINE, which WordPress never needs.
*/
define( 'DB_NAME', te_env( 'DB_NAME' ) );
define( 'DB_USER', te_env( 'DB_USER' ) );
define( 'DB_PASSWORD', te_env( 'DB_PASSWORD' ) );
define( 'DB_HOST', te_env( 'DB_HOST', 'localhost' ) );
define( 'DB_CHARSET', 'utf8mb4' );
define( 'DB_COLLATE', '' );
/**
* Custom table prefix. The default 'wp_' is documented in every SQL injection
* payload ever written; a custom prefix turns most of them into no-ops at the
* query level. The prefix must match what's actually in your database; if you're
* migrating an existing site, do NOT change this without also renaming all the
* tables (export, rename every table in the export, import, then update this).
*
* Pick something short, 3-8 characters, lowercase, ending with underscore.
*/
$table_prefix = 'mysite_';
// ============================================================
// Authentication unique keys and salts
// ============================================================
/**
* WordPress uses these 8 constants to hash login cookies, nonces, and other
* secret material. They MUST be unique per site and MUST NOT be the placeholder
* values from the sample file. Generate fresh ones every time you set up a site
* AND every time you suspect compromise (rotating these invalidates every
* existing session, which is exactly what you want during incident response).
*
* Generate at: https://api.wordpress.org/secret-key/1.1/salt/
* and put the values in .env (never in this file).
*/
define( 'AUTH_KEY', te_env( 'AUTH_KEY' ) );
define( 'SECURE_AUTH_KEY', te_env( 'SECURE_AUTH_KEY' ) );
define( 'LOGGED_IN_KEY', te_env( 'LOGGED_IN_KEY' ) );
define( 'NONCE_KEY', te_env( 'NONCE_KEY' ) );
define( 'AUTH_SALT', te_env( 'AUTH_SALT' ) );
define( 'SECURE_AUTH_SALT', te_env( 'SECURE_AUTH_SALT' ) );
define( 'LOGGED_IN_SALT', te_env( 'LOGGED_IN_SALT' ) );
define( 'NONCE_SALT', te_env( 'NONCE_SALT' ) );
// ============================================================
// File system and updates
// ============================================================
/**
* Disable the in-admin file editor.
*
* Without this, an administrator (or anyone who took over an admin account)
* can edit theme and plugin PHP files directly through Appearance > Theme File
* Editor and Plugins > Plugin File Editor. That writes PHP to disk through the
* browser, which is the primary way stolen admin credentials get turned into
* persistent backdoors. Disabling the editor doesn't stop legitimate updates;
* it only stops the manual through-the-UI edit path.
*
* This is one of the two single most important hardening directives. The other
* is FORCE_SSL_ADMIN below.
*/
define( 'DISALLOW_FILE_EDIT', true );
/**
* Disable plugin and theme installation, updates, and deletion through the admin.
*
* Stronger than DISALLOW_FILE_EDIT alone, this prevents an admin from installing
* a new plugin entirely. Combined with DISALLOW_FILE_EDIT, the only way to
* modify or add code to the site is through SSH/SFTP plus deployment process.
* For sites with a real release process, that's correct. For sites where
* admins legitimately install plugins, this is too restrictive.
*
* Set true if your deployment is git-based or automated; leave false if admins
* legitimately install plugins through the admin.
*/
define( 'DISALLOW_FILE_MODS', false );
/**
* How WordPress writes files. 'direct' uses standard file functions (fastest
* and works when the web user owns the WordPress directory); 'ssh2' uses SSH
* (requires the ssh2 PHP extension); 'ftpext' and 'ftpsockets' use FTP.
*
* 'direct' is correct for any deployment where the web user owns wp-content/.
* Anything else means files are getting written by a different user, which
* leads to permission confusion and is usually a sign of misconfigured hosting.
*/
define( 'FS_METHOD', 'direct' );
/**
* Auto-update WordPress core minor releases (security patches).
*
* Possible values:
* true Auto-update everything (major + minor + dev + translations)
* false Auto-update nothing
* 'minor' Auto-update minor releases only
*
* 'minor' is the right answer. Security patches arrive without intervention;
* major version upgrades remain manual (so you can test and roll back if a
* theme or plugin breaks). Without the constant, WordPress follows the
* Updates screen setting and the install's default: minor-only for sites
* from before 5.6, minor AND major for new installs since 5.6. Setting it
* explicitly pins the policy and overrides the dashboard toggle.
*/
define( 'WP_AUTO_UPDATE_CORE', 'minor' );
// ============================================================
// HTTPS and admin access
// ============================================================
/**
* Force SSL for the admin area and the login form.
*
* Without this, an admin who happens to load /wp-admin/ over HTTP sends their
* authentication cookie unencrypted. On any shared WiFi, that's an immediate
* session hijack. This directive redirects HTTP admin/login requests to HTTPS
* before any cookie is read.
*
* Requires that your site has a working HTTPS certificate (Let's Encrypt is
* free and automated). Don't enable this on a site that doesn't have HTTPS yet
* or admins will be locked out.
*/
define( 'FORCE_SSL_ADMIN', true );
/**
* Set the canonical site URLs explicitly. Without this, WordPress derives the
* URL from the HTTP_HOST header on each request, which is attacker-influenced.
* Setting these constants pins the URLs to known-good values regardless of
* what the request claims.
*
* The values come from .env so this file stays identical across environments:
* set WP_HOME and WP_SITEURL in each environment's .env (for example
* https://yoursite.com in production, https://yoursite.local on a laptop).
* They should always start with https://, never http://, on a hardened site.
*/
define( 'WP_HOME', te_env( 'WP_HOME' ) );
define( 'WP_SITEURL', te_env( 'WP_SITEURL', te_env( 'WP_HOME' ) ) );
/**
* Trust the X-Forwarded-Proto header from your reverse proxy.
*
* If WordPress sits behind Cloudflare, Nginx, or any reverse proxy that
* terminates SSL and forwards to WordPress over HTTP, this lets WordPress
* detect that the original request was HTTPS and generate correct https://
* URLs in the output.
*
* Comment out (or leave commented) if WordPress receives requests directly
* over HTTPS without a proxy.
*/
// if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] )
// && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
// $_SERVER['HTTPS'] = 'on';
// }
// ============================================================
// Cron
// ============================================================
/**
* Disable WP-Cron's page-load trigger.
*
* By default, every request to WordPress checks scheduled events and runs any
* that are due. This is unreliable (events fire only when traffic happens; a
* low-traffic site can miss scheduled jobs entirely) and exposed (anyone can
* trigger cron by hitting /wp-cron.php, which DoS-attackers sometimes abuse).
*
* Set this to true, then add a system cron entry that runs due events every
* 5 or 15 minutes (the crontab lines are below the template; they cannot sit
* in this comment, because the cron step syntax would close the docblock).
*/
define( 'DISABLE_WP_CRON', true );
/**
* Wp-Cron lock timeout. If a cron event takes longer than 60 seconds and a
* second request comes in, the second wp_cron call would normally try to run
* the same events again. The lock timeout prevents that. Default is 60 in
* recent WordPress versions; setting it explicitly is documentation.
*/
define( 'WP_CRON_LOCK_TIMEOUT', 60 );
// ============================================================
// Debug and error handling
// ============================================================
/**
* Enable debug logging on, debug display off.
*
* WP_DEBUG=true tells WordPress to surface errors and warnings.
* WP_DEBUG_LOG writes them to a log file: true logs to wp-content/debug.log,
* or pass a path to log outside the web root (this template uses
* /var/log/wordpress/debug.log, set below).
* WP_DEBUG_DISPLAY=false suppresses the output in the page, so visitors don't
* see "Notice: Undefined index ..." (which leaks information about your code
* structure and is sometimes useful for attackers fingerprinting plugin
* versions).
*
* In production, you want errors logged where you can review them but never
* shown to visitors. SCRIPT_DEBUG and SAVEQUERIES stay false in production;
* they expand log volume and add overhead.
*/
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', '0' );
define( 'SCRIPT_DEBUG', false );
define( 'SAVEQUERIES', false );
/**
* Custom path for the debug log. The default location (wp-content/debug.log)
* is web-accessible if your web server is misconfigured. Putting it outside
* the document root, in a path the web server can write but not serve, removes
* that risk.
*
* Adjust the path to match your server layout. Make sure the directory is
* writable by the web user (chmod 750, chown www-data:www-data).
*/
define( 'WP_DEBUG_LOG', '/var/log/wordpress/debug.log' );
// ============================================================
// Content limits
// ============================================================
/**
* Limit the number of post revisions stored per post.
*
* Default is unlimited. On a site that gets edited often, this bloats the
* database significantly. A reasonable cap is 10 revisions per post; that's
* enough to roll back recent edits but not enough to balloon storage.
*
* Set to false to disable revisions entirely, or any integer for a cap.
*/
define( 'WP_POST_REVISIONS', 10 );
/**
* Auto-save interval in seconds. Default 60 (one save per minute). On a slow
* MySQL or shared host, 60 seconds is too aggressive and contributes to
* Database is unable to keep up errors. 120 or 180 is gentler.
*/
define( 'AUTOSAVE_INTERVAL', 120 );
/**
* Trash retention. Default 30 days. Shorter is better for security (deleted
* content stays gone) but means a finger-slipped delete is unrecoverable.
* 7 days is a reasonable compromise.
*/
define( 'EMPTY_TRASH_DAYS', 7 );
// ============================================================
// Memory and limits
// ============================================================
/**
* PHP memory limit for the public site. 256M is enough for almost every site.
* Increase if a specific plugin (page builders, large image processing, bulk
* imports) needs more, but treat any limit above 512M as a red flag worth
* profiling. See https://techearl.com/how-to-increase-php-memory-limit for the
* cases where this matters and how to diagnose memory pressure.
*/
define( 'WP_MEMORY_LIMIT', '256M' );
/**
* Separate limit for the admin area. Bulk operations (plugin updates, theme
* customization, large media uploads) sometimes need more memory than the
* public site. 384M for admin is reasonable.
*/
define( 'WP_MAX_MEMORY_LIMIT', '384M' );
// ============================================================
// Multisite (only if applicable)
// ============================================================
/**
* Uncomment if this is a multisite install. Leave commented for single sites.
*
* The full multisite block requires several more constants; see
* https://wordpress.org/documentation/article/create-a-network/
*/
// define( 'WP_ALLOW_MULTISITE', true );
// define( 'MULTISITE', true );
// define( 'SUBDOMAIN_INSTALL', false );
// define( 'DOMAIN_CURRENT_SITE', 'yoursite.com' );
// define( 'PATH_CURRENT_SITE', '/' );
// define( 'SITE_ID_CURRENT_SITE', 1 );
// define( 'BLOG_ID_CURRENT_SITE', 1 );
// ============================================================
// End of custom settings
// ============================================================
/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
define( 'ABSPATH', __DIR__ . '/' );
}
/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';The system cron entry that replaces the page-load trigger, in the web user's crontab:
*/5 * * * * curl -s https://yoursite.com/wp-cron.php?doing_wp_cron > /dev/null
# or, more cleanly, with WP-CLI:
*/5 * * * * wp cron event run --due-now --path=/var/www/wordpress > /dev/nullThe two directives that matter most are DISALLOW_FILE_EDIT (a stolen admin account can no longer write PHP to disk through the theme and plugin editors) and FORCE_SSL_ADMIN (the admin cookie never travels over HTTP). Leaving DISALLOW_FILE_MODS false is the usual middle ground: nobody edits code through the UI, but admins can still install plugins. Set it true only when every code change comes through a deployment.
File permissions for wp-config.php
Set the file so the web user can read it and nothing else on the server can:
# Owner = the web user; group = the web group; permissions = 600
sudo chown www-data:www-data /var/www/wordpress/wp-config.php
sudo chmod 600 /var/www/wordpress/wp-config.phpWith 600, other users on the server (and any other site's PHP-FPM pool running as a different user, see cross-site contamination) cannot read the file at all. If 600 breaks the site because the host runs PHP as a different user than the file owner, try 640 with the web server's group. Do not go broader than 644; wider read permissions defeat the purpose.
Directives I leave out
WP_HTTP_BLOCK_EXTERNALblocks every outbound HTTP request, which also breaks core, plugin and theme updates, Gravatar, oEmbed previews, Akismet and most analytics. Use it only on an air-gapped install.CONCATENATE_SCRIPTSfalse trades a minor admin performance issue for more requests. Leave the default.COOKIE_DOMAINis occasionally needed for multisite with domain mapping; on a single site WordPress derives the right value.DISALLOW_UNFILTERED_HTMLstops stored XSS through post content but also stops legitimate raw HTML (an<iframe>embed, custom HTML widgets). Turn it on only if editors do not need raw HTML.FORCE_SSL_LOGINis the older directiveFORCE_SSL_ADMINsuperseded in WordPress 4.0. Setting both is redundant.- Plugin-specific constants belong with the plugin, because they silently do nothing the day it is removed. The one I do reach for is
define( 'WORDFENCE_DISABLE_LIVE_TRAFFIC', true );, which hard-disables the Live Traffic mode whose beacons flood Search Console with ?wordfence_lh=1 URLs.
Common wp-config mistakes
- Placeholder salts. Copying
wp-config-sample.phpby hand and leaving'put your unique phrase here'means every cookie is signed with a public phrase, so anyone can forge an admin cookie. Generate fresh salts athttps://api.wordpress.org/secret-key/1.1/salt/and put them in.env. Rotating them invalidates every session, which is what you want during incident response. - Forcing HTTPS without a valid certificate.
FORCE_SSL_ADMINon a site without working HTTPS locks admins out. Confirm the certificate renews first. WP_DEBUG_LOGwithoutWP_DEBUG_DISPLAYfalse. Errors get logged and also printed to visitors, leaking paths, plugin versions and sometimes SQL fragments. Set both together, and keep the log outsidewp-content/, where a misconfigured server can serve it.- Changing
$table_prefixafter install. WordPress immediately queries tables that do not exist. Change it only by exporting the database, renaming every table, importing, and then updating$table_prefix. - A database user with more than it needs. The scope matters:
GRANT ALL ON *.*hands over the globalFILE,PROCESSandSUPERprivileges a SQL-injected query can abuse, whileGRANT ALL ON your_database.*only covers database-level privileges (noFILE,PROCESSorSUPER) but still addsTRIGGER,EVENT,CREATE ROUTINEand friends that WordPress never uses. Check what the account really has withSHOW GRANTS FOR 'your_user'@'localhost';, then grant the minimal set:
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER,
CREATE TEMPORARY TABLES, LOCK TABLES, REFERENCES
ON `your_database`.* TO 'your_user'@'localhost';
FLUSH PRIVILEGES;- A world-readable file. At
644, anything on the server, including other sites' PHP on shared hosting, can read whatever secrets remain in the file.chmod 600it.
After applying the template: generate fresh salts, tighten the MySQL grant, set the permissions, confirm the site, admin, plugin updates and HTTPS redirects all work, add the system cron line that replaces WP-Cron's page-load trigger, and put wp-config.php under server-side file integrity monitoring so it never changes without a deliberate action.
For database credentials and salts, load it near the top of wp-config.php, above the require_once ABSPATH . 'wp-settings.php'; line, because WordPress reads DB_NAME and friends before any plugin runs.
For plugin API keys and other non-core secrets, you can load (or just read) from a must-use plugin instead, since those values are not needed that early. If the .env is already loaded in wp-config.php, the values are in $_ENV by the time the MU-plugin runs, so you only read them, you do not load the file twice.
Must-use plugins load through a simpler path than regular plugins: WordPress only includes the PHP files directly inside mu-plugins/, never files in subdirectories. A top-level loader file has to require the bootstrap from the subdirectory by hand.
No, register_activation_hook() never fires for them. Move one-time setup (creating a table, seeding an option, flushing rewrite rules) onto init, gated by an option check so it runs once and is a no-op afterwards.
Only if you follow the three must-dos. The win is keeping secrets out of git: add .env to .gitignore, keep the file outside the web root (or block HTTP access to it), and commit a blank .env.example instead.
Skip those and it is worse than the default, because you have created a plaintext credentials file in your web root. A .env served at /.env with a 200 response hands an attacker every secret in one request.
Dotenv::createImmutable() will not overwrite a variable that is already set in the real environment, so a value exported by your server or container wins over the matching line in the file. That is the safe default: the .env acts as a local fallback that production env vars can override.
createMutable() lets the file clobber existing environment variables. Reach for it only when you specifically need the file to take precedence, which is uncommon.
Everything in a .env file is a string. WP_DEBUG=false reads back as the string "false", which PHP treats as truthy, so debug mode stays on when you meant to turn it off.
Run boolean-ish values through filter_var( $value, FILTER_VALIDATE_BOOLEAN ) so that false, 0, and off all resolve to a real PHP false before you pass them to define().
Treat every secret in that file as compromised and rotate it: change the database password, regenerate the WordPress salts, and reissue any API keys that were in the file. Deleting the file in a new commit does not help, because the values still sit in your git history.
Then add .env to .gitignore so it cannot happen again, and if the repo is shared or public, consider rewriting history to purge the file in addition to rotating the credentials.
In the root of your WordPress installation, alongside wp-load.php, wp-settings.php, and index.php. On cPanel-managed hosting it is commonly at ~/public_html/wp-config.php.
WordPress also looks one directory up from the install root, so /var/www/wp-config.php works if /var/www/wordpress/ is the install.
WordPress supports it, and it protects against a server misconfigured to serve .php as text. That failure is very rare on properly configured Apache and Nginx; the bigger risk is other tenants reading the file on shared hosting, which chmod 600 fixes. I set the permissions and leave the file where it is.
The .env is different: it is a plain-text file, not PHP, so a web server will happily serve it. That is why it belongs above the web root even when wp-config.php does not.
Not directly. It only disables the two in-admin file editors (Theme File Editor and Plugin File Editor). Plugins that write to wp-content/uploads/, install themselves, or update themselves go through different code paths and keep working.
The only thing it breaks is editing theme or plugin PHP through the browser, which is fragile, unversioned, and exactly the path an attacker uses after stealing admin credentials.
A custom prefix is not a fundamental defense, but most automated SQL injection payloads hard-code the default wp_ prefix, so a custom one makes those generic payloads fail. A targeted attacker can probe for your prefix; mass-scanning bots do not.
Set one on new installs. Retrofitting an existing site means renaming every table, which is usually not worth it unless you are already migrating.
WP_DEBUG is the master switch that surfaces notices, warnings, and deprecations. WP_DEBUG_LOG writes them to a file (default wp-content/debug.log, or a path you pass). WP_DEBUG_DISPLAY controls whether they render in the page.
For production, log to a path outside the document root and set WP_DEBUG_DISPLAY to false, so every problem is recorded and none is shown to visitors.
Some (Solid Security, formerly iThemes, Defender, MalCare) write a subset on activation, usually DISALLOW_FILE_EDIT, FORCE_SSL_ADMIN and the debug settings. They skip the choices they cannot safely automate: the table prefix, a debug log path off the document root, and the MySQL grant.
They are a fine starting point, but walk the full template yourself on a production site.
See also
- Send WordPress email through SendGrid: a textbook case of an API key that belongs in
.envrather than a plugin's settings table - Clean up wp_head in WordPress: the same "do not hand visitors something the server should never serve" instinct, applied to the default head output
- How to Remove WordPress Malware: the cleanup methodology a hardened wp-config.php makes cheaper
- WordPress File Integrity Monitoring That Can't Be Disabled: the layer that catches an unauthorized change to the hardened file
- How to Increase PHP Memory Limit: the diagnostic process behind the template's memory constants
- How to optimize WooCommerce: where per-environment config really earns its keep, since staging and production routinely point at different databases and services
Sources
Authoritative references this article was fact-checked against.
- vlucas/phpdotenv: GitHub repository and READMEgithub.com
- The Twelve-Factor App: Config12factor.net
- Editing wp-config.php: WordPress Developer Referencedeveloper.wordpress.org
- WordPress, Hardening WordPress (official documentation)wordpress.org
- WordPress, Editing wp-config.php (official documentation)wordpress.org
- WordPress, Debugging in WordPress (official documentation)wordpress.org
- MySQL 8.4 Reference Manual: GRANT statement (privilege levels)dev.mysql.com
- phpdotenv UPGRADING guide (V5: createImmutable no longer calls putenv)github.com
- Upgrading WordPress (automatic background updates, WP_AUTO_UPDATE_CORE)developer.wordpress.org
- Must-Use Plugins: WordPress Developer documentationdeveloper.wordpress.org
- The composer.json schema (autoload / PSR-4): Composer documentationgetcomposer.org
- PSR-4: Autoloader: PHP-FIGphp-fig.org





