Как найти файл wp config php

Topics

  • Configure Database Settings
    • Default wp-config-sample.php
      • Set Database Name
      • Set Database User
      • Set Database Password
      • Set Database Host
    • Database character set
    • Database collation
    • Security Keys
  • Advanced Options
    • table_prefix
    • WP_SITEURL
    • Blog address (URL)
    • Moving wp-content folder
    • Moving plugin folder
    • Moving themes folder
    • Moving uploads folder
    • Modify AutoSave Interval
    • Post Revisions
      • Disable Post Revisions
      • Specify the Number of Post Revisions
    • Set Cookie Domain
    • Enable Multisite / Network Ability
    • Redirect Nonexistent Blogs
    • Fatal Error Handler
    • WP_DEBUG
    • WP_ENVIRONMENT_TYPE
    • SCRIPT_DEBUG
    • Disable Javascript Concatenation
    • Configure Error Logging
    • Increasing memory allocated to PHP
    • Cache
    • Custom User and Usermeta Tables
    • Language and Language Directory
      • WordPress v3.9.6 and below
    • Save queries for analysis
    • Override of default file permissions
    • WordPress Upgrade Constants
      • Enabling SSH Upgrade Access
    • Alternative Cron
    • Disable Cron and Cron Timeout
    • Additional Defined Constants
    • Empty Trash
    • Automatic Database Optimizing
    • DO_NOT_UPGRADE_GLOBAL_TABLES
    • View All Defined Constants
    • Disable the Plugin and Theme File Editor
    • Disable Plugin and Theme Update and Installation
    • Require SSL for Admin and Logins
    • Block External URL Requests
    • Disable WordPress Auto Updates
    • Disable WordPress Core Updates
    • Cleanup Image Edits
  • Double Check Before Saving

One of the most important files in your WordPress installation is the wp-config.php file. This file is located in the root of your WordPress file directory and contains your website’s base configuration details, such as database connection information.

Important: Never use a word processor like Microsoft Word for editing WordPress files!

Locate the file wp-config-sample.php in the base directory of your WordPress directory and open in a text editor.

Note: This is an example of a default wp-config-sample.php. The values here are examples to show you what to do.

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );
/** MySQL database username */
define( 'DB_USER', 'username_here' );
/** MySQL database password */
define( 'DB_PASSWORD', 'password_here' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

Note: Text inside /* */ are comments, for information purposes only.

Replace ‘database_name_here’, with the name of your database, e.g. MyDatabaseName.

define( 'DB_NAME', 'MyDatabaseName' ); // Example MySQL database name

Replace ‘username_here’, with the name of your username e.g. MyUserName.

define( 'DB_USER', 'MyUserName' ); // Example MySQL username

Replace ‘password_here’, with the your password, e.g. MyPassWord.

define( 'DB_PASSWORD', 'MyPassWord' ); // Example MySQL password

Replace ‘localhost’, with the name of your database host, e.g. MyDatabaseHost. A port number or Unix socket file path may be needed as well.

define( 'DB_HOST', 'MyDatabaseHost' ); // Example MySQL Database host

Note: There is a good chance you will NOT have to change it. If you are unsure, try installing with the default value of ‘localhost’ and see if it works. If the install fails, contact your web hosting provider.

MySQL Alternate Port

If your host uses an alternate port number for your database you’ll need to change the DB_HOST value in the wp-config.php file to reflect the alternate port provided by your host.

For localhost:

define( 'DB_HOST', '127.0.0.1:<strong>3307' );
or
define( 'DB_HOST', 'localhost:<strong>3307' );

For specified server:

define( 'DB_HOST', 'mysql.example.com:<strong>3307' );

Replace 3307 with whatever port number your host gives you.

MySQL Sockets or Pipes

If your host uses Unix sockets or pipes, adjust the DB_HOST value in the wp-config.php file accordingly.

define( 'DB_HOST', '127.0.0.1:<strong>/var/run/mysqld/mysqld.sock' );
// or define( 'DB_HOST', 'localhost:<strong>/var/run/mysqld/mysqld.sock' );
// or define( 'DB_HOST', 'example.tld:<strong>/var/run/mysqld/mysqld.sock' );

Replace /var/run/mysqld/mysqld.sock with the socket or pipe information provided by your host.

DB_CHARSET was made available to allow designation of the database character set (e.g. tis620 for TIS620 Thai) to be used when defining the MySQL database tables.

The default value of utf8 (Unicode UTF-8) is almost always the best option. UTF-8 supports any language, so you typically want to leave DB_CHARSET at utf8 and use the DB_COLLATE value for your language instead.

This example shows utf8 which is considered the WordPress default value:

define( 'DB_CHARSET', 'utf8' );

There usually should be no reason to change the default value of DB_CHARSET. If your blog needs a different character set, please read Character Sets and Collations MySQL Supports for valid DB_CHARSET values. WARNING: Those performing upgrades.

If DB_CHARSET and DB_COLLATE do not exist in your wp-config.php file, DO NOT add either definition to your wp-config.php file unless you read and understand Converting Database Character Sets. Adding DB_CHARSET and DB_COLLATE to the wp-config.php file, for an existing blog, can cause major problems.

DB_COLLATE was made available to allow designation of the database collation (i.e. the sort order of the character set). In most cases, this value should be left blank (null) so the database collation will be automatically assigned by MySQL based on the database character set specified by DB_CHARSET. An example of when you may need to set ”’DB_COLLATE”’ to one of the UTF-8 values defined in UTF-8 character sets for most Western European languages would be when a different language in which the characters that you entered are not the same as what is being displayed. (See also Unicode Character Sets in SQL Manual)

The WordPress default DB_COLLATE value:

define( 'DB_COLLATE', '' );

UTF-8 Unicode General collation

define( 'DB_COLLATE', 'utf8_general_ci' );

UTF-8 Unicode Turkish collation

define( 'DB_COLLATE', 'utf8_turkish_ci' );

There usually should be no reason to change the default value of DB_COLLATE. Leaving the value blank (null) will insure the collation is automatically assigned by MySQL when the database tables are created. WARNING: Those performing upgrades

If DB_COLLATE and DB_CHARSET do not exist in your wp-config.php file, DO NOT add either definition to your wp-config.php file unless you read and understand Converting Database Character Sets. And you may be in need of a WordPress upgrade.

You don’t have to remember the keys, just make them long, random and complicated — or better yet, use the online generator. You can change these at any point in time to invalidate all existing cookies. This does mean that all users will have to login again.

Example (don’t use these!):

define( 'AUTH_KEY',         't`DK%X:>xy|e-Z(BXb/f(Ur`8#~UzUQG-^_Cs_GHs5U-&Wb?pgn^p8(2@}IcnCa|' );
define( 'SECURE_AUTH_KEY',  'D&ovlU#|CvJ##uNq}bel+^MFtT&.b9{UvR]g%ixsXhGlRJ7q!h}XWdEC[BOKXssj' );
define( 'LOGGED_IN_KEY',    'MGKi8Br(&{H*~&0s;{k0<S(O:+f#WM+q|npJ-+P;RDKT:~jrmgj#/-,[hOBk!ry^' );
define( 'NONCE_KEY',        'FIsAsXJKL5ZlQo)iD-pt??eUbdc{_Cn<4!d~yqz))&B D?AwK%)+)F2aNwI|siOe' );
define( 'AUTH_SALT',        '7T-!^i!0,w)L#JK@pc2{8XE[DenYI^BVf{L:jvF,hf}zBf883td6D;Vcy8,S)-&G' );
define( 'SECURE_AUTH_SALT', 'I6`V|mDZq21-J|ihb u^q0F }F_NUcy`l,=obGtq*p#Ybe4a31R,r=|n#=]@]c #' );
define( 'LOGGED_IN_SALT',   'w<$4c$Hmd%/*]`Oom>(hdXW|0M=X={we6;Mpvtg+V.o<$|#_}qG(GaVDEsn,~*4i' );
define( 'NONCE_SALT',       'a|#h{c5|P &xWs4IZ20c2&%4!c(/uG}W:mAvy<I44`jAbup]t=]V<`}.py(wTP%%' );

A secret key makes your site harder to successfully attack by adding random elements to the password.

In simple terms, a secret key is a password with elements that make it harder to generate enough options to break through your security barriers. A password like “password” or “test” is simple and easily broken. A random, long password which uses no dictionary words, such as “88a7da62429ba6ad3cb3c76a09641fc” would take a brute force attacker millions of hours to crack. A ‘salt is used to further enhance the security of the generated result.

The four keys are required for the enhanced security. The four salts are recommended, but are not required, because WordPress will generate salts for you if none are provided. They are included in wp-config.php by default for inclusiveness.

For more information on the technical background and breakdown of secret keys and secure passwords, see:

  • Ryan Boren – SSL and Cookies in WordPress 2.6
  • Wikipedia’s explanation of Password Cracking
  • Lorelle VanFossen – Protect Your Blog With a Solid Password
  • Instructables – Security Password Tips
  • Huffington Post – 17 Tips You Can Do Today to Protect Your Online Passwords

The following sections may contain advanced information and some changes might result in unforeseen issues. Please make sure you practice regular backups and know how to restore them before modifying these settings.

The $table_prefix is the value placed in the front of your database tables. Change the value if you want to use something other than wp_ for your database prefix. Typically this is changed if you are installing multiple WordPress blogs in the same database, as is done with the multisite feature.

It is possible to have multiple installations in one database if you give each a unique prefix. Keep security in mind if you choose to do this.

$table_prefix = 'r235_'; // Only numbers, letters, and underscores please!

WP_SITEURL allows the WordPress address (URL) to be defined. The value defined is the address where your WordPress core files reside. It should include the http:// part too. Do not put a slash “/” at the end. Setting this value in wp-config.php overrides the wp_options table value for siteurl. Adding this in can reduce the number of database calls when loading your site. Note: This will not change the database stored value. The URL will revert to the old database value if this line is ever removed from wp-config. Use the RELOCATE constant to change the siteurl value in the database.

If WordPress is installed into a directory called “wordpress” for the domain example.com, define WP_SITEURL like this:

define( 'WP_SITEURL', 'http://example.com/wordpress' );

Dynamically set WP_SITEURL based on $_SERVER[‘HTTP_HOST’]

define( 'WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress' );

Note: HTTP_HOST is created dynamically by PHP based on the value of the HTTP HOST Header in the request, thus possibly allowing for file inclusion vulnerabilities. SERVER_NAME may also be created dynamically. However, when Apache is configured as UseCanonicalName “on”, SERVER_NAME is set by the server configuration, instead of dynamically. In that case, it is safer to user SERVER_NAME than HTTP_HOST.

Dynamically set WP_SITEURL based on $_SERVER[‘SERVER_NAME’]

define( 'WP_SITEURL', 'http://' . $_SERVER['SERVER_NAME'] . '/path/to/wordpress' );

Similar to WP_SITEURL, WP_HOME overrides the wp_options table value for home but does not change it in the database. home is the address you want people to type in their browser to reach your WordPress blog. It should include the http:// part and should not have a slash “/” at the end. Adding this in can reduce the number of database calls when loading your site.

define( 'WP_HOME', 'http://example.com/wordpress' );

If you are using the technique described in Giving WordPress Its Own Directory then follow the example below. Remember, you will also be placing an index.php in your web-root directory if you use a setting like this.

define( 'WP_HOME', 'http://example.com' );

Dynamically set WP_HOME based on $_SERVER[‘HTTP_HOST’]

define( 'WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress' );

You can move the wp-content directory, which holds your themes, plugins, and uploads, outside of the WordPress application directory.

Set WP_CONTENT_DIR to the full local path of this directory (no trailing slash), e.g.

define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/blog/wp-content' );

Set WP_CONTENT_URL to the full URL of this directory (no trailing slash), e.g.

define( 'WP_CONTENT_URL', 'http://example/blog/wp-content' );

Set WP_PLUGIN_DIR to the full local path of this directory (no trailing slash), e.g.

define( 'WP_PLUGIN_DIR', dirname(__FILE__) . '/blog/wp-content/plugins' );

Set WP_PLUGIN_URL to the full URI of this directory (no trailing slash), e.g.

define( 'WP_PLUGIN_URL', 'http://example/blog/wp-content/plugins' );

If you have compability issues with plugins Set PLUGINDIR to the full local path of this directory (no trailing slash), e.g.

define( 'PLUGINDIR', dirname(__FILE__) . '/blog/wp-content/plugins' );

You cannot move the themes folder because its path is hardcoded relative to the wp-content folder:

$theme_root = WP_CONTENT_DIR . ‘/themes’;

However, you can register additional theme directories using register_theme_directory.

See how to move the wp-content folder. For more details how the themes folder is determined, see wp-includes/theme.php.

Set UPLOADS to :

define( 'UPLOADS', 'blog/wp-content/uploads' );

This path can not be absolute. It is always relative to ABSPATH, therefore does not require a leading slash.

When editing a post, WordPress uses Ajax to auto-save revisions to the post as you edit. You may want to increase this setting for longer delays in between auto-saves, or decrease the setting to make sure you never lose changes. The default is 60 seconds.

define( 'AUTOSAVE_INTERVAL', 160 ); // Seconds

WordPress, by default, will save copies of each edit made to a post or page, allowing the possibility of reverting to a previous version of that post or page. The saving of revisions can be disabled, or a maximum number of revisions per post or page can be specified.

If you do not set this value, WordPress defaults WP_POST_REVISIONS to true (enable post revisions). If you want to disable the awesome revisions feature, use this setting:

define( 'WP_POST_REVISIONS', false );

Note: Some users could not get this to function until moving the command to the first line under the initial block comment in wp-config.php.

If you want to specify a maximum number of revisions that WordPress stores, change false to an integer/number (e.g., 3 or 12).

define( 'WP_POST_REVISIONS', 3 );

Note: Some users could not get this to function until moving the command to the first line under the initial block comment in wp-config.php.

The domain set in the cookies for WordPress can be specified for those with unusual domain setups. For example, if subdomains are used to serve static content, you can set the cookie domain to only your non-static domain to prevent WordPress cookies from being sent with each request to static content on your subdomain .

define( 'COOKIE_DOMAIN', 'www.example.com' );

WP_ALLOW_MULTISITE is a feature enable multisite functionality. If this setting is absent from wp-config.php it defaults to false.

define( 'WP_ALLOW_MULTISITE', true );

NOBLOGREDIRECT can be used to redirect the browser if the visitor tries to access a nonexistent subdomain or a subfolder.

define( 'NOBLOGREDIRECT', 'http://example.com' );

WordPress 5.2 introduced Recovery Mode which displays error message instead of white screen when plugins causes fatal error.

The site is experiencing technical difficulties. Please check your site admin email inbox for instructions.

White screens and PHP error messages are not displayed to users any more. But in a development environment, if you want to enable WP_DEBUG_DISPLAY, you have to disable recovery mode by set true to WP_DISABLE_FATAL_ERROR_HANDLER.

define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );   // 5.2 and later define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', true ); 

The WP_DEBUG option controls the reporting of some errors and warnings and enables use of the WP_DEBUG_DISPLAY and WP_DEBUG_LOG settings. The default boolean value is false.

define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );   // 5.2 and later
define( 'WP_DEBUG', true );

Database errors are printed only if WP_DEBUG is set to true. Database errors are handled by the wpdb class and are not affected by PHP’s error settings.

Setting WP_DEBUG to true also raises the error reporting level to E_ALL and activates warnings when deprecated functions or files are used; otherwise, WordPress sets the error reporting level to E_ALL ^ E_NOTICE ^ E_USER_NOTICE.

The WP_ENVIRONMENT_TYPE option controls the environment type for a site: local, development, staging, and production.

The values of environment types are processed in the following order with each sequential method overriding any previous values: the WP_ENVIRONMENT_TYPE PHP environment variable and the WP_ENVIRONMENT_TYPE constant.

For both methods, if the value of an environment type provided is not in the list of allowed environment types, the default production value will be returned.

The simplest way to set the value is probably through defining the constant:

define( 'WP_ENVIRONMENT_TYPE', 'staging' );

Note: When development is returned by wp_get_environment_type() , WP_DEBUG will be set to true if it is not defined in the wp-config.php file of the site.

SCRIPT_DEBUG is a related constant that will force WordPress to use the “dev” versions of scripts and stylesheets in wp-includes/js, wp-includes/css, wp-admin/js, and wp-admin/css will be loaded instead of the .min.css and .min.js versions.. If you are planning on modifying some of WordPress’ built-in JavaScript or Cascading Style Sheets, you should add the following code to your config file:

define( 'SCRIPT_DEBUG', true );

To result in faster administration screens, all JavaScript files are concatenated into one URL. If JavaScript is failing to work in an administration screen, you can try disabling this feature:

define( 'CONCATENATE_SCRIPTS', false );

Configuring error logging can be a bit tricky. First of all, default PHP error log and display settings are set in the php.ini file, which you may or may not have access to. If you do, they should be set to the desired settings for live PHP pages served to the public. It’s strongly recommended that no error messages are displayed to the public and instead routed to an error log. Further more, error logs should not be located in the publicly accessible portion of your server. Sample recommended php.ini error settings:

error_reporting = 4339
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /home/example.com/logs/php_error.log
log_errors_max_len = 1024
ignore_repeated_errors = On
ignore_repeated_source = Off
html_errors = Off

About Error Reporting 4339

This is a custom value that only logs issues that affect the functioning of your site, and ignores things like notices that may not even be errors. See PHP Error Constants for the meaning of each binary position for 1000011110011, which is the binary number equal to 4339. The far left 1 means report any E_RECOVERABLE_ERROR. The next 0 means do not report E_STRICT, (which is thrown when sloppy but functional coding is used) and so on. Feel free to determine your own custom error reporting number to use in place of 4339.

Obviously, you will want different settings for your development environment. If your staging copy is on the same server, or you don’t have access to php.ini, you will need to override the default settings at run time. It’s a matter of personal preference whether you prefer errors to go to a log file, or you prefer to be notified immediately of any error, or perhaps both. Here’s an example that reports all errors immediately that you could insert into your wp-config.php file:

@ini_set( 'log_errors', 'Off' );
@ini_set( 'display_errors', 'On' );
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );   // 5.2 and later
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', false );
define( 'WP_DEBUG_DISPLAY', true );

Because wp-config.php is loaded for every page view not loaded from a cache file, it is an excellent location to set php.ini settings that control your PHP installation. This is useful if you don’t have access to a php.ini file, or if you just want to change some settings on the fly. One exception is ‘error_reporting’. When WP_DEBUG is defined as true, ‘error_reporting’ will be set to E_ALL by WordPress regardless of anything you try to set in wp-config.php. If you really have a need to set ‘error_reporting’ to something else, it must be done after wp-settings.php is loaded, such as in a plugin file.

If you turn on error logging, remember to delete the file afterwards, as it will often be in a publicly accessible location, where anyone could gain access to your log.

Here is an example that turns PHP error_logging on and logs them to a specific file. If WP_DEBUG is defined to true, the errors will also be saved to this file. Just place this above any require_once or include commands.

@ini_set( 'log_errors', 'On' );
@ini_set( 'display_errors', 'Off' );
@ini_set( 'error_log', '/home/example.com/logs/php_error.log' );
/* That's all, stop editing! Happy blogging. */

Another example of logging errors, as suggested by Mike Little on the wp-hackers email list:

/**
 * This will log all errors notices and warnings to a file called debug.log in
 * wp-content (if Apache does not have write permission, you may need to create
 * the file first and set the appropriate permissions (i.e. use 666) )
 */
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

A refined version from Mike Little on the Manchester WordPress User Group:

/**
 * This will log all errors notices and warnings to a file called debug.log in
 * wp-content only when WP_DEBUG is true. if Apache does not have write permission,
 * you may need to create the file first and set the appropriate permissions (i.e. use 666).
 */
define( 'WP_DEBUG', true ); // Or false
if ( WP_DEBUG ) {
    define( 'WP_DEBUG_LOG', true );
    define( 'WP_DEBUG_DISPLAY', false );
    @ini_set( 'display_errors', 0 );
}

Confusing the issue is that WordPress has three (3) constants that look like they could do the same thing. First off, remember that if WP_DEBUG is false, it and the other two WordPress DEBUG constants do not do anything. The PHP directives, whatever they are, will prevail. Except for ‘error_reporting’, WordPress will set this to 4983 if WP_DEBUG is defined as false. Second, even if WP_DEBUG is true, the other constants only do something if they too are set to true. If they are set to false, the PHP directives remain unchanged. For example, if your php.ini file has the directive (‘display_errors’ = ‘On’); but you have the statement define( ‘WP_DEBUG_DISPLAY’, false ); in your wp-config.php file, errors will still be displayed on screen even though you tried to prevent it by setting WP_DEBUG_DISPLAY to false because that is the PHP configured behavior. This is why it’s very important to set the PHP directives to what you need in case any of the related WP constants are set to false. To be safe, explicitly set/define both types. More detailed descriptions of the WP constants is available at Debugging in WordPress.

For your public, production WordPress installation, you might consider placing the following in your wp-config.php file, even though it may be partly redundant:

@ini_set( 'log_errors', 'On' );
@ini_set( 'display_errors', 'Off' );
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', false );   // 5.2 and later
define( 'WP_DEBUG', false );
define( 'WP_DEBUG_LOG', false );
define( 'WP_DEBUG_DISPLAY', false );

The default debug log file is /wp-content/debug.log. Placing error logs in publicly accessible locations is a security risk. Ideally, your log files should be placed above you site’s public root directory. If you can’t do this, at the very least, set the log file permissions to 600 and add this entry to the .htaccess file in the root directory of your WordPress installation:

<Files debug.log>
    Order allow,deny
    Deny from all
</Files>

This prevents anyone from accessing the file via HTTP. You can always view the log file by retrieving it from your server via FTP.

WP_MEMORY_LIMIT option allows you to specify the maximum amount of memory that can be consumed by PHP. This setting may be necessary in the event you receive a message such as “Allowed memory size of xxxxxx bytes exhausted”.

This setting increases PHP Memory only for WordPress, not other applications. By default, WordPress will attempt to increase memory allocated to PHP to 40MB (code is at the beginning of /wp-includes/default-constants.php) for single site and 64MB for multisite, so the setting in wp-config.php should reflect something higher than 40MB or 64MB depending on your setup.

WordPress will automatically check if PHP has been allocated less memory than the entered value before utilizing this function. For example, if PHP has been allocated 64MB, there is no need to set this value to 64M as WordPress will automatically use all 64MB if need be.

Note: Some hosts do not allow for increasing the PHP memory limit automatically. In that event, contact your host to increase the PHP memory limit. Also, many hosts set the PHP limit at 8MB.

Adjusting the WordPress memory limit potentially creates problems as well. You might end up hiding the root of the issue for it to happen later down the line as you add in more plugins or functionalities.

If you are facing Out of Memory issues even with an elevated memory limit, you should properly debug your installation. Chances are you have too many memory intensive functions tied to a specific action and should move these functions to a cronjob.

Increase PHP Memory to 64MB

define( 'WP_MEMORY_LIMIT', '64M' );

Increase PHP Memory to 96MB

define( 'WP_MEMORY_LIMIT', '96M' );

Administration tasks require may require memory than usual operation. When in the administration area, the memory can be increased or decreased from the WP_MEMORY_LIMIT by defining WP_MAX_MEMORY_LIMIT.

define( 'WP_MAX_MEMORY_LIMIT', '128M' );

Note: this has to be put before wp-settings.php inclusion.

The WP_CACHE setting, if true, includes the wp-content/advanced-cache.php script, when executing wp-settings.php.

define( 'WP_CACHE', true );

CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE are used to designate that the user and usermeta tables normally utilized by WordPress are not used, instead these values/tables are used to store your user information.

define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' );
define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' );

Note: Even if ‘CUSTOM_USER_META_TABLE’ is manually set, a usermeta table is still created for each database with the corresponding permissions for each instance. By default, the WordPress installer will add permissions for the first user (ID #1). You also need to manage permissions to each of the site via a plugin or custom function. If this isn’t setup you will experience permission errors and log-in issues.

CUSTOM_USER_TABLE is easiest to adopt during initial Setup your first instance of WordPress. The define statements of the wp-config.php on the first instance point to where wp_users data will be stored by default. After the first site setup, copying the working wp-config.php to your next instance will only require a change the $table_prefix variable. Do not use an e-mail address that is already in use by your original install. Once you have finished the setup process log in with the auto generated admin account and password. Next, promote your normal account to the administrator level and Log out of admin. Log back in as yourself, delete the admin account and promote the other user accounts as is needed.

WordPress Version 4.0 allows you to change the language in your WordPress Administration Screens. To change the language in the admin settings screen. Go to Settings > General and select Site Language.

WPLANG defines the name of the language translation (.mo) file. WP_LANG_DIR defines what directory the WPLANG .mo file resides. If WP_LANG_DIR is not defined WordPress looks first to wp-content/languages and then wp-includes/languages for the .mo defined by WPLANG file.

define( 'WPLANG', 'de_DE' );
define( 'WP_LANG_DIR', dirname(__FILE__) . 'wordpress/languages' );

To find out the WPLANG language code, please refer here. The code in WP Local column is what you need.

The SAVEQUERIES definition saves the database queries to an array and that array can be displayed to help analyze those queries. The information saves each query, what function called it, and how long that query took to execute. Note: This will have a performance impact on your site, so make sure to turn this off when you aren’t debugging.

First, add this to the wp-config.php file:

define( 'SAVEQUERIES', true );

Then in the footer of your theme put this:

if ( current_user_can( 'administrator' ) ) {
    global $wpdb;
    echo "<pre>";
    print_r( $wpdb->queries );
    echo "</pre>";
}
?>

Alternatively, consider using Query Monitor

The FS_CHMOD_DIR and FS_CHMOD_FILE define statements allow override of default file permissions. These two variables were developed in response to the problem of the core update function failing with hosts running under suexec. If a host uses restrictive file permissions (e.g. 400) for all user files, and refuses to access files which have group or world permissions set, these definitions could solve the problem.

define( 'FS_CHMOD_DIR', ( 0755 & ~ umask() ) );
define( 'FS_CHMOD_FILE', ( 0644 & ~ umask() ) );

Example to provide setgid:

define( 'FS_CHMOD_DIR', ( 02755 & ~umask() ) );

Note: ‘0755′ and ‘02755‘ are octal values. Octal values must be prefixed with a 0 and are not delineated with single quotes (‘). See Also: Changing File Permissions

Note: Define as few of the below constants as needed to correct your update issues.

The most common causes of needing to define these are:

Host running with a special installation setup involving symlinks. You may need to define the path-related constants (FTP_BASE, FTP_CONTENT_DIR, and FTP_PLUGIN_DIR). Often defining simply the base will be enough.

Certain PHP installations shipped with a PHP FTP extension which is incompatible with certain FTP servers. Under these rare situations, you may need to define FS_METHOD to “ftpsockets”.

The following are valid constants for WordPress updates:

  • FS_METHOD forces the filesystem method. It should only be “direct”, “ssh2”, “ftpext”, or “ftpsockets”. Generally, you should only change this if you are experiencing update problems. If you change it and it doesn’t help, change it back/remove it. Under most circumstances, setting it to ‘ftpsockets’ will work if the automatically chosen method does not.
    • (Primary Preference) “direct” forces it to use Direct File I/O requests from within PHP, this is fraught with opening up security issues on poorly configured hosts, This is chosen automatically when appropriate.
    • (Secondary Preference) “ssh2” is to force the usage of the SSH PHP Extension if installed
    • (3rd Preference) “ftpext” is to force the usage of the FTP PHP Extension for FTP Access, and finally
    • (4th Preference) “ftpsockets” utilises the PHP Sockets Class for FTP Access.
  • FTP_BASE is the full path to the “base”(ABSPATH) folder of the WordPress installation.
  • FTP_CONTENT_DIR is the full path to the wp-content folder of the WordPress installation.
  • FTP_PLUGIN_DIR is the full path to the plugins folder of the WordPress installation.
  • FTP_PUBKEY is the full path to your SSH public key.
  • FTP_PRIKEY is the full path to your SSH private key.
  • FTP_USER is either user FTP or SSH username. Most likely these are the same, but use the appropriate one for the type of update you wish to do.
  • FTP_PASS is the password for the username entered for FTP_USER. If you are using SSH public key authentication this can be omitted.
  • FTP_HOST is the hostname:port combination for your SSH/FTP server. The default FTP port is 21 and the default SSH port is 22. These do not need to be mentioned.
  • FTP_SSL TRUE for SSL-connection if supported by the underlying transport (not available on all servers). This is for “Secure FTP” not for SSH SFTP.
define( 'FS_METHOD', 'ftpext' );
define( 'FTP_BASE', '/path/to/wordpress/' );
define( 'FTP_CONTENT_DIR', '/path/to/wordpress/wp-content/' );
define( 'FTP_PLUGIN_DIR ', '/path/to/wordpress/wp-content/plugins/' );
define( 'FTP_PUBKEY', '/home/username/.ssh/id_rsa.pub' );
define( 'FTP_PRIKEY', '/home/username/.ssh/id_rsa' );
define( 'FTP_USER', 'username' );
define( 'FTP_PASS', 'password' );
define( 'FTP_HOST', 'ftp.example.org' );
define( 'FTP_SSL', false );

Some configurations should set FTP_HOST to localhost to avoid 503 problems when trying to update plugins or WP itself.

There are two ways to upgrade using SSH2.

The first is to use the SSH SFTP Updater Support plugin. The second is to use the built-in SSH2 upgrader, which requires the pecl SSH2 extension be installed.

To install the pecl SSH2 extension you will need to issue a command similar to the following or talk to your web hosting provider to get this installed:

pecl install ssh2

After installing the pecl ssh2 extension you will need to modify your PHP configuration to automatically load this extension.

pecl is provided by the pear package in most linux distributions. To install pecl in Redhat/Fedora/CentOS:

yum -y install php-pear

To install pecl in Debian/Ubuntu:

apt-get install php-pear

It is recommended to use a private key that is not pass-phrase protected. There have been numerous reports that pass phrase protected private keys do not work properly. If you decide to try a pass phrase protected private key you will need to enter the pass phrase for the private key as FTP_PASS, or entering it in the “Password” field in the presented credential field when installing updates.

There might be reason to use an alternative Cron with WP. Most commonly this is done if scheduled posts are not getting published as predicted. This alternative method uses a redirection approach. The users’ browser get a redirect when the cron needs to run, so that they come back to the site immediately while cron continues to run in the connection they just dropped. This method has certain risks, since it depends on a non-native WordPress service.

define( 'ALTERNATE_WP_CRON', true );

Disable cron entirely by setting DISABLE_WP_CRON to true.

define( 'DISABLE_WP_CRON', true );

Make sure a cron process cannot run more than once every WP_CRON_LOCK_TIMEOUT seconds.

define( 'WP_CRON_LOCK_TIMEOUT', 60 );

Here are additional constants that can be defined. These probably shouldn’t be set unless other methodologies have been attempted first. The Cookie definitions can be particularly useful if you have an unusual domain setup.

define( 'COOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'home' ) . '/' ) );
define( 'SITECOOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'siteurl' ) . '/' ) );
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );
define( 'PLUGINS_COOKIE_PATH', preg_replace( '|https?://[^/]+|i', '', WP_PLUGIN_URL ) );
define( 'TEMPLATEPATH', get_template_directory() );
define( 'STYLESHEETPATH', get_stylesheet_directory() );

This constant controls the number of days before WordPress permanently deletes posts, pages, attachments, and comments, from the trash bin. The default is 30 days:

define( 'EMPTY_TRASH_DAYS', 30 ); // 30 days

To disable trash set the number of days to zero.

define( 'EMPTY_TRASH_DAYS', 0 ); // Zero days

Note: WordPress will not ask for confirmation when someone clicks on “Delete Permanently” using this setting.

There is automatic database repair support, which you can enable by adding the following define to your wp-config.php file.

Note: This should only be enabled if needed and disabled once the issue is solved. When enabled, a user does not need to be logged in to access the functionality, since its main intent is to repair a corrupted database and users can often not login when the database is corrupt.

 define( 'WP_ALLOW_REPAIR', true );

The script can be found at {$your_site}/wp-admin/maint/repair.php.

A DO_NOT_UPGRADE_GLOBAL_TABLES define prevents dbDelta() and the upgrade functions from doing expensive queries against global tables.

Sites that have large global tables (particularly users and usermeta), as well as sites that share user tables with bbPress and other WordPress installs, can prevent the upgrade from changing those tables during upgrade by defining DO_NOT_UPGRADE_GLOBAL_TABLES to true. Since an ALTER, or an unbounded DELETE or UPDATE, can take a long time to complete, large sites usually want to avoid these being run as part of the upgrade so they can handle it themselves. Further, if installations are sharing user tables between multiple bbPress and WordPress installs you may to want one site to be the upgrade master.

define( 'DO_NOT_UPGRADE_GLOBAL_TABLES', true );

PHP has a function that returns an array of all the currently defined constants with their values.

 print_r( @get_defined_constants() );

Occasionally you may wish to disable the plugin or theme file editor to prevent overzealous users from being able to edit sensitive files and potentially crash the site. Disabling these also provides an additional layer of security if a hacker gains access to a well-privileged user account.

define( 'DISALLOW_FILE_EDIT', true );

Note: The functionality of some plugins may be affected by the use of current_user_can('edit_plugins') in their code. Plugin authors should avoid checking for this capability, or at least check if this constant is set and display an appropriate error message. Be aware that if a plugin is not working this may be the cause.

This will block users being able to use the plugin and theme installation/update functionality from the WordPress admin area. Setting this constant also disables the Plugin and Theme File editor (i.e. you don’t need to set DISALLOW_FILE_MODS and DISALLOW_FILE_EDIT, as on its own DISALLOW_FILE_MODS will have the same effect).

define( 'DISALLOW_FILE_MODS', true );

Note: WordPress Version 4.0 deprecated FORCE_SSL_LOGIN. Please use FORCE_SSL_ADMIN.

FORCE_SSL_ADMIN is for when you want to secure logins and the admin area so that both passwords and cookies are never sent in the clear. See also Administration_Over_SSL for more details.

define( 'FORCE_SSL_ADMIN', true );

Block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true and this will only allow localhost and your blog to make requests. The constant WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted.

define( 'WP_HTTP_BLOCK_EXTERNAL', true );
define( 'WP_ACCESSIBLE_HOSTS', 'api.wordpress.org,*.github.com' );

There might be reason for a site to not auto-update, such as customizations or host supplied updates. It can also be done before a major release to allow time for testing on a development or staging environment before allowing the update on a production site.

 define( 'AUTOMATIC_UPDATER_DISABLED', true );

The easiest way to manipulate core updates is with the WP_AUTO_UPDATE_CORE constant:

 # Disable all core updates:
 define( 'WP_AUTO_UPDATE_CORE', false );
 # Enable all core updates, including minor and major:
 define( 'WP_AUTO_UPDATE_CORE', true );
 # Enable core updates for minor releases (default):
 define( 'WP_AUTO_UPDATE_CORE', 'minor' );

Reference: Disabling Auto Updates in WordPress 3.7

By default, WordPress creates a new set of images every time you edit an image and when you restore the original, it leaves all the edits on the server. Defining IMAGE_EDIT_OVERWRITE as true changes this behaviour. Only one set of image edits are ever created and when you restore the original, the edits are removed from the server.

 define( 'IMAGE_EDIT_OVERWRITE', true );

Be sure to check for leading and/or trailing spaces around any of the above values you entered, and DON’T delete the single quotes!

Before you save the file, be sure to double-check that you have not accidentally deleted any of the single quotes around the parameter values. Be sure there is nothing after the closing PHP tag in the file. The last thing in the file should be ?> and nothing else. No spaces.

To save the file, choose File > Save As > wp-config.php and save the file in the root of your WordPress install. Upload the file to your web server and you’re ready to install WordPress!

wp-config.php – ключевой конфигурационный файл WordPress, загружающийся до запуска ядра. Не входит в инсталляционный пакет CMS, обычно генерируется «движком» во время установки сайта. С помощью этого файла подключается ваша база данных MySQL и устанавливается ее префикс, обеспечивается хранение ключей шифрования, включается режим отладки, указывается путь к директории WordPress, задаются глобальные значения констант PHP.

Полезный плагин

A-Feed: автонаполнение вашего WordPress-сайта. Обзор плагина.

Редактировать wp-config.php стоит только в том случае, если точно знаете, что именно делаете. Перед каждой модификацией файла крайне рекомендуется делать резервную копию. Если что-то пойдет не так, вы в любой момент сможете восстановить рабочую конфигурацию, зайдя в корневой каталог вашего сайта WordPress файловым менеджером, FileZilla или другим FTP-клиентом. 

В инсталляционном пакете файла wp-config.php нет, но есть шаблон wp-config-sample.php. при установке WordPress через FTP, CMS просит ввести название базы данных, имя и пароль пользователя, сервер БД MySQL, префикс таблиц. После этого движок автоматически копирует файл примера в корень, переименовывает его в wp-config.php и прописывает в нем введенные вами значения фиксированных переменных.    

Ответ на вопрос, где находится wp-config.php, обычно лежит в корневой директории вашего ресурса, рядом с другими служебными файлами WordPress и каталогами wp-admin, wp-includes, wp-content. Однако в типовом месте размещения есть существенный недостаток – здесь главный конфигурационный скрипт CMS становится легкой мишенью для злоумышленников. Многие плагины безопасности предлагают опцию перемещения wp-config в другую папку в качестве одного из шагов по усилению защиты сайта на WordPress.      

Для чего нужен файл wp-config.php

зачем нужен wp-config.php

В базовой конфигурации CMS в главном файле системы управления сайтом задаются:

  • ключевые параметры подключения базы данных (БД);
  • ключи безопасности; // шифрование хранящихся в браузере паролей;
  • префикс таблицы БД; // wp_ по умолчанию, но рекомендуется более сложный префикс;
  • константа ABSPATH, указывающая путь к корневой директории.

Параметры подключения БД определяются фиксированными переменными:

  • DB_NAME – тип данных text, значение – текущее название БД MySQL;
  • DB_USER – текстовый тип данных, имя пользователя;
  • DB_HOST – имя хоста (домен, IP-адрес, опционально – +номер порта);
  • DB_PASSWORD – тип данных text, пароль БД MySQL;
  • DB_CHARSET – кодировка текста таблиц БД;
  • DB_COLLATE – тип сравнения для БД.

Параметр DB_HOST чаще всего принимает значение ‘localhost’, однако у многих хостеров дефолтные значения этой фиксированной переменной отличаются. Например, Yahoo использует хост ‘mysql’, 1and1 Hosting – db12345679. Если не подходит ‘localhost’, уточните корректное значение у своего провайдера услуг хостинга. Значение $_ENV{DATABASE_SERVER} даст на выходе функции define актуальный хост базы данных. С помощью константы DB_HOST можно указать и альтернативный порт хоста MySQL. Номер порта указывается после двоеточия. Например, ‘localhost:х’, где ‘х’ – новое глобальное значение порта.

В скрипте wp-config могут определяться и другие фиксированные константы языка сценариев PHP, не входящие в базовый функционал.

Принципы работы с файлом wp-config.php

как работает wp-config.php

Некорректные установки wp-config.php могут вызвать сбои или полностью заблокировать загрузку сайта и доступ к панели администрирования. Поэтому при работе с основным конфигурационным файлом ресурса рекомендуется соблюдать следующие меры предосторожности:

  • делайте резервные копии главного скрипта WordPress перед каждой модификацией файла конфигурации;
  • вносите изменения в wp-config.php только в том случае, если уверены на 100% в своих действиях.

Базовая конфигурация изначально находится в файле примера wp-config-sample.php. Сценарий инсталляции CMS копирует этот файл в корневую директорию, присваивает константам значения, введенные пользователем во время установки WordPress, и сохраняет результаты в скрипте wp-config.php. Если что-то пойдет не так, пользователю может понадобиться прописать нужные значения вручную. Для этого придется зайти в корень сайта с помощью файлового менеджера или FTP-клиента.

Настройки БД, ключи и путь к корневому каталогу, где находится wp-config.php, определяются функцией define(), принимающей на входе название константы, а на выходе дающей ее значение. С помощью этой функции глобально переопределяются и другие константы PHP. Формат записи:

define (‘КОНСТАНТА’, ‘значение_константы’);

Примеры:

define (‘DB_HOST’, ‘localhost’); // задаем сервер базы данных;

define (‘DB_CHARSET’, ‘utf8’); // определяем кодировку текста таблиц БД, рекомендуется UTF-8;

Полный перечень констант PHP, их тип и значения по умолчанию можно найти в Кодексе WordPress, официальном справочнике самой популярной CMS мира. Например, за включение и отключение режима отладки отвечает фиксированная переменная ‘WP_DEBUG’. Дебаг относится к логическому типу данных и может принимать значения ‘true’ (отладка включена) или ‘false’ (режим отладки отключен).

Примеры:

define ( ‘WPLANG’, ‘ru_RU’ ); // устаревшая константа указания файла локализации (до WP 4.0);

define ( ‘DISABLE_WP_CRON’, true ); // отключение cron, по умолчанию значение ‘false’;

define ( ‘EMPTY_TRASH_DAYS’, false ); // отключение корзины, по умолчанию включена;

программный код, возможно wp-config.php

В WordPress 4.0 фиксированная переменная WPLANG заменена функцией get_locale(), устанавливающей локаль и получающей текущий индекс языка сайта (например, en_US для английского (США) или ru_RU для русского). Начиная с WP 5.0, вместо функции get_locale() обычно используется обертка determine_locale().

Константа EMPTY_TRASH_DAYS показывает, сколько суток должны храниться в корзине стертые записи перед их окончательным удалением. Значение по умолчанию – 30 [дней]. Фиксированной переменной можно изменить период времени нахождения записей в корзине или полностью отключить корзину (значение – false). Есть возможность отключить корзину только для файлов медиа (видео, аудио, изображения). Делается это с помощью «переключателя» MEDIA_TRASH, принимающего два значения – ‘false’ (функция отключена) или ‘true’ (медиафайлы отправляются в корзину и хранятся там столько суток, сколько определено константой EMPTY_TRASH_DAYS).      

Для получения пути и URL каталога плагинов можно воспользоваться константами WP_PLUGIN_DIR и WP_PLUGIN_URL. За настройки автоматического обновления ядра отвечает фиксированная переменная WP_AUTO_UPDATE_CORE. Она может принимать значения ‘true’, ‘false’ или ‘minor’. True – автообновление включено. False – отключение автоматического апдейта. Minor – включение обновлений только для незначительных релизов.

Фиксированная переменная WP_MEMORY_LIMIT задает предельный объем ROM под выполнение скриптов WordPress. По умолчанию для сценариев выделяется 32 Мб, в режиме Multisite выставляется дефолтное значение 64 Мб. Обычно такого количества памяти хватает. Если же из-за превышения лимита наблюдаются сбои или полностью блокируется работа сайта на CMS WordPress, не стоит торопиться со смягчением ограничений. Возможно, есть смысл отказаться от «прожорливых» сценариев и плагинов и заменить их на более «легкое» ПО с меньшими требованиями к программно-аппаратной части сервера.

В wp-config.php можно задать значения еще нескольких десятков фиксированных переменных. Все они определяются глобально, поскольку главный конфигурационный файл сайта загружается еще до запуска ядра CMS. Полный список констант PHP смотрите в официальной документации WordPress.

Полезная статья

Выбор хостинга для WordPress

Заключение

Задаваемая wp-config.php конфигурация – один из ключевых элементов обеспечения стабильной работы сайта на системе управления WordPress. Поэтому, еще раз повторимся, перед любой модификацией файла крайне рекомендуется сделать его резервную копию. Стоит подумать и о переносе wp-config.php в другой каталог. Нетиповое место размещение главного конфигурационного файла снижает уязвимость сайта при целом ряде хакерских атак. Это можно сделать либо вручную, либо с помощью одного из плагинов безопасности.

Наш канал на YouTube

What is wp-config.php in WordPress?

The wp-config.php file is a WordPress installation core file containing the details of your website’s most crucial configuration settings. The prefix ‘wp’ stands for ‘WordPress,’ ‘config’ is short for ‘configuration,’ and the file type ‘.php’ indicates the type of code contained in the file — PHP. 

Without wp-config.php, your website simply wouldn’t function. WordPress requires this file, most importantly, to connect to your database where information like WordPress settings, post content, theme and plugin settings, and user data is all stored. Not only is wp-config.php the bridge between your site’s files and your database, it also allows you to include security keys; change table prefixes; relocate core WordPress file folders like wp-plugins, wp-uploads, and wp-content; and perform other advanced configurations.

Where is the wp-config.php file located?

Now that you know what wp-config.php does, you’re probably wondering, “Where is wp-config.php located?” If you’re looking for the location of wp-config.php in an already existing WordPress site, you’ll find it in the root folder of your WordPress installation. Your root folder contains the wp-admin, wp-content, and wp-includes folders. Beneath these folders, you will see a list of files, many of which begin with the ‘wp-’ prefix. This is where you’ll find your wp-config.php file.

list of core files and folders, with wp-config.php selected

If you’re downloading and setting up WordPress for the first time, however, the wp-config.php file will not be included. Instead, it will be created automatically during the WordPress setup process. During setup, you’ll be asked for certain information like: 

  • Database Name: Name of the database associated with your WordPress installation
  • Database Username: Username used to access your database
  • Database Password: Password associated with the database user
  • Database Host: The hostname of your database server (usually ‘localhost’ but can vary depending on your hosting provider)

WordPress will then use this information to create the wp-config.php file in your root directory. 

database connection details form

You can also manually set up wp-config.php, if you prefer. This might be a good option if you have a lot of customized settings you’d like to add to your site’s configuration. 

How do I access wp-config.php?

There are a couple of simple methods for accessing wp-config.php — through secure file transfer protocol (SFTP) or through cPanel, if your hosting company provides it. 

1. Accessing wp-config.php via SFTP

Step 1: Install your SFTP client. Your first step will be to download and install an SFTP client if you don’t have one already. Several good options include: 

Application System Free or Premium
WinSCP Windows Free
Filezilla  Windows, Mac, Linux Free and premium options
Cyberduck Windows, Mac Free
Transmit Mac Premium

We’ll be using Filezilla for this example, but other SFTP clients should work similarly.

Step 2: Retrieve your SFTP credentials. Once you’ve installed your SFTP client, you’ll need SFTP credentials from your web host in order to access your server. You’ll find these details in your hosting control panel. Depending on your host, this information may be generated for you or you may have to go through the process of creating an SFTP username and password. If you’re unsure where to find these credentials or how to create them, ask your host’s support or search their help documentation for instructions. The details you’ll need for your SFTP client are:

  • Host (your live server’s IP address or url)
  • SFTP username
  • Password
  • Port number

Step 3: Enter your credentials in your SFTP client. Enter your host’s IP address or url, your SFTP username, password, and the port number.

Note: If your SFTP client uses trust on first use (TOFU) authentication, you may get a ‘host key unknown’ alert. Click ‘OK’ and proceed. Check ‘Always trust this host, add this key to the cache’ if you plan on using your SFTP client to access the site again. 

TOFU message from Filezilla

Step 4: Navigate to your website’s root directory.

Once you’ve logged into your server via SFTP, you’ll see a file tree displayed in the right-bottom two panels of your screen which lists the directories on your web server (remote). The left side lists the directories from your computer (local). 

Your root directory is usually in a folder labeled “www” or “public_html,” but it might use a different name. Root folder naming conventions differ on some hosts, so if you aren’t sure what folder to look in, ask your hosting provider. You’ll know you’re in the correct folder if you see the wp-admin, wp-content, and wp-includes folders near the top of your file list.

finding the public_html folder via FTP

Step 5: Select or create a folder on your local computer where you want to add your wp-config.php file. If you already have a folder selected, use the left pane to navigate to and open it. If not, find the directory where you’d like to create a new folder, right click on the left pane, and select Create directory.

create directory selection

Name your directory and then click OK.

Double click to open the new directory you created.

Step 6: Find and download wp-config.php. The wp-config.php file is located in your root folder, so just scroll down to wp-config.php in the bottom right pane of your SFTP client. Right click on the wp-config.php, and click Download, or simply drag the file from the right pane to the desired folder in the left pane.

downloading the wp-config.php file

Your wp-config.php file should now be downloaded to your local machine in the directory you selected previously. You should be able to find it in your computer’s file browser.

2. Accessing wp-config.php in cPanel

If your host uses cPanel, you can access wp-config.php through cPanel’s file manager. If you don’t know how to find cPanel in your host’s dashboard, contact their customer support for help. 

Step 1: Open cPanel’s File Manager. Once you’re in cPanel, navigate to the Files section and click on File Manager.

Step 2: Open your website’s root folder. The root folder is commonly called ‘www’ or ‘public_html,’ but it may have another name. Root folder naming conventions differ on some hosts, so if you aren’t sure what folder to look in, ask your hosting provider. You’ll know you’re in the correct folder if you see the wp-admin, wp-content, and wp-includes folders near the top of your file list.

Step 3: Find and download wp-config.php. The wp-config.php file is located in your root folder, so just scroll down to wp-config.php in the right pane of cPanel’s File Manager. Right click on the wp-config.php, and click Download, or single-click wp-config.php and then click the Download option from the top menu.

dowloading wp-config.php from cpanel

Select or create a folder where you want to place your wp-config.php file (do NOT rename it) and click Save

choosing a folder to save wp-config.php to

Your wp-config.php file should now be downloaded to your local machine in the directory you selected. You should be able to find it in your computer’s file browser.

How to edit your wp-config.php file

There are two options for editing wp-config.php. You can either use a source code editor or you edit it directly in cPanel. Before you edit the wp-config.php file in WordPress, always make sure you back up your site!

1. Back up your site 

Any time you make a major change to your site — especially to WordPress core files or plugins — you run the risk of something going wrong. It could be something as minor as a hardly-perceptible display issue to the dreaded white screen of death. To prevent downtime and data loss when making changes to core aspects of your site, always make a backup first. If you don’t have a backup tool installed on your site already, Jetpack Backup is an affordable solution with one-click restores.

All backed up? Good. We can start editing the wp-config.php file.

2. How to edit wp-config.php with a source code editor

The best way to edit wp-config.php is in your code editing software of choice. Since you’re editing a copy of wp-config.php that is offline on your local computer, you don’t have to be connected to the internet to work on your file and you’re less likely to overwrite your original wp-config.php file when you upload it back to your server (unlike editing directly in cPanel). 

Step 1: Open wp-config.php in your source code editor. If you aren’t familiar with using a source code editor, there are several free options to choose from. 

Free source code and plain text editors:

Application System
Notepad++ Windows
Atom.io Windows, Mac, Linux
Sublime Windows, Mac, Linux
TextEdit
*make sure you’re in plain text mode
Mac (default application)
Notepad Windows (default application)

Step 2: Edit wp-config.php and save it to your local machine. Your display may look different depending on what program you use to edit your wp-config.php file. This is what some of the code looks like in atom.io:

content of the wp-config.php file

Add or change whatever information you need to, then save your file. Skip to ‘What can you configure via wp-config.php?’ to learn more about the different types of edits you can make to your wp-config.php file.

Step 3: Log in to your web server via SFTP or cPanel. Navigate to your site’s root folder and find the wp-config.php file.

Step 4: Change the file name of wp-config.php on your web server. In case your edited version contains errors, you don’t want to overwrite your original file. You want to be able to restore the original wp-config.php file quickly, so renaming it to something like ‘wp-config-orginal.php’ will not only ensure that WordPress ignores this file but that the contents of the original file still exist on your server.

renaming the wp-config.php file

If you accidentally overwrite your wp-config.php file and your edited version has issues, you can always restore your site from a backup. However, it’s always a good idea to retain a copy of your original wp-config.php file for a quick restore should something go wrong. If you don’t have a backup file somewhere — especially if you have a lot of custom settings — it may be a huge hassle and cause lots of site downtime to recover the original information.

Step 5: Upload wp-config.php from your local machine to your webserver. Using SFTP or cPanel, upload your wp-config.php file to your web server’s root directory.

SFTP client:

moving the wp-config.php file via ftp

cPanel:

uploading a file via cpanel

Step 6: Visit your website and test that it’s displaying and functioning correctly. You’ve successfully uploaded your wp-config.php file, so now it’s time to make sure that everything is working on your site as you intended. Visit the front end of your site and also log in to the WordPress dashboard to make sure everything is accessible, displays correctly, and that site functionality like forms, navigation, eCommerce features, etc. all work. 

Step 7: Delete the old, renamed wp-config.php file. Once you’ve established that your site is functioning properly, you can delete wp-config-original.php (or whatever you renamed it to).

3. How to edit wp-config.php directly in your cPanel

If you don’t have or don’t want to use a source code editor, you can edit wp-config.php directly in cPanel (if your host uses cPanel). This is a little more risky than editing on your local machine. If your internet connection is disrupted while you’re editing, you could lose your changes. You also run the risk of potentially overwriting your original wp-config.php file without first saving a backup. But as long as you make a copy of your original wp-config.php file and have a reliable internet connection, you should be relatively safe editing directly in cPanel. 

Step 1: Find wp-config.php in cPanel. In cPanel, click on ‘File Manager.’ 

Navigate to your root folder (usually ‘public_html’ or ‘www’ but, depending on your host, it may be called something else).

Step 2: Create a new folder for your wp-config.php backup file. In your File Manager main menu, click + Folder to add a new folder. We’ll be making a copy of your wp-config.php file and saving it here as a backup.

adding a folder in cpanel

Name your new folder something easy to identify like ‘backup config’ so you can easily find it later. Click Create New Folder.

Step 3: Find wp-config.php in the root folder and copy it to the backup folder. In your root directory, scroll down to wp-config.php and right click on the file name. Select Copy.

A dialog box will appear asking you to enter the file path you want to copy the file to. It will usually have the root folder name prepopulated, so you should only need to add the name of the backup folder you just created after ‘/public_html/’ (or whatever your root folder is named). So if your backup folder is named ‘backup config,’ your file path would be something like ‘/public_html/backup config.

Click Copy File(s).

Once you’ve copied the file over, navigate to your ‘backup config’ folder and you’ll see wp-config.php listed there. You should go ahead and rename this just so you don’t get this wp-config.php file and the one you want to edit confused. Right click the wp-config.php file and click Rename

You can rename it to whatever you want, but in this case we’ll rename it to wp-config-original.php.

renaming the wp-config.php file

Step 4: Navigate back to wp-config.php in the root directory. Now that we have a backup of our wp-config.php file, we’ll go back to the wp-config.php file in the root directory to edit it. 

Select wp-config.php, then click Edit in the top menu of File Manager.

editing via cpanel tools

Step 5: Edit wp-config.php. You should now see the contents of the wp-config.php file on your screen. It should look something like this: 

the wp-config.php file in cpanel

Add or change whatever information you need to, then save your file. Skip to ‘What can you configure via wp-config.php?’ to learn more about the different types of edits you can make to your wp-config.php file.

Creating the wp-config.php file manually

You can’t edit your wp-config.php file if you haven’t created one yet! If for some reason, you’re unable to create the wp-config.php file during WordPress setup or you’d simply prefer to create it manually, you’ll want to use the wp-config-sample.php template that’s included when you download WordPress.

finding the wp-config-sample.php file

Open wp-config-sample.php in your source code editor. Your display may look different depending on what program you use to edit your wp-config-sample.php file. This is what some of the code looks like in atom.io:

content of the wp-config.php file

Enter the following database details and any custom settings you may need: 

The name of the database for WordPress

define( 'DB_NAME', 'database_name_here' ); 

Database user name

define( 'DB_USER', 'username_here' ); 

Database password

define( 'DB_PASSWORD', 'password_here' ); 

Database hostname

define( 'DB_HOST', 'localhost' );

Database charset to use in creating database tables (usually utf8)

define( 'DB_CHARSET', 'utf8' );

Database collate type (don’t change this if in doubt)

define( 'DB_COLLATE', '' );

Authentication unique keys and salts

Change these to different unique phrases. You can generate these using the WordPress.org secret-key service. These can be changed at any time to invalidate all existing cookies. Just keep in mind that this will force all users to have to log in again.

define( 'AUTH_KEY',  'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',  'put your unique phrase here' );
define( 'NONCE_KEY',  'put your unique phrase here' );
define( 'AUTH_SALT',  'put your unique phrase here' );
define( 'SECURE_AUTH_SALT',  'put your unique phrase here' );
define( 'LOGGED_IN_SALT',  'put your unique phrase here' );
define( 'NONCE_SALT',  'put your unique phrase here' );

Define custom WordPress database table prefix

The default database table prefix for WordPress is ‘wp_’, but you can define a custom prefix if you like. Also, if you have multiple installations of WordPress in one database, you can give each a unique prefix. Use only numbers, letters, and underscores.

$table_prefix = 'wp_';

Define WordPress debugging mode

By default, WordPress debugging mode in wp-config.php should be set to ‘false’ unless you’re in development mode and actively trying to debug issues on your site. 

define( 'WP_DEBUG', false );

Change this statement to ‘true’ to enable the display of error and warning notices during development. 

Add custom values

There are two commented out lines of code after your line defining debugging mode, in between which you can add any custom values you’d like to add to your wp-config.php file.

/* Add any custom values between this line and the "stop editing" line. */
YOUR CUSTOM VALUES GO HERE
/* That's all, stop editing! Happy publishing. */

For information on custom values that can be used, scroll down to the section ‘What can you configure via wp-config.php?.

Define the absolute path to the WordPress directory

Below your custom values, after ‘/*That’s all, stop editing! Happy publishing.*/,’ you’ll see a couple other code snippets. The first one defines the absolute path to the WordPress directory. You can leave this as-is unless you’ve set WordPress up in a subdirectory — in which case you would replace ‘/’ with  ‘/your-subdirectory/’. 

if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}

Set up WordPress vars and included files

This last section in your wp-config-sample.php file declares the absolute path to wp-settings.php, which sets up WordPress vars and included files.

require_once ABSPATH . 'wp-settings.php';

When you’re done editing your sample config file, save it as ‘wp-config.php’ and place it in your site’s root directory using SFTP or cPanel.

NOTE: There’s a specific order to the contents of the wp-config-sample.php file and the order is important. Rearranging the order of information in your configuration file may create errors on your site. 

What can you configure in wp-config.php?

There are a lot of things you can configure with wp-config.php beyond the basic settings included in the wp-config-sample.php file. You can enable multisite functionality, set cookie domains, increase allowed memory, manage a variety of security related settings, determine the frequency with which WordPress performs certain core operations, and change other file optimization settings. You can even make changes to your database and file permissions. 

What can’t you configure in wp-config.php?

While the list of settings that you can manage in wp-config.php is long, there are some things that you can’t do. 

The wp-config.php file is more or less a list of constants that determine certain settings within WordPress core. You can’t use it to make any functional modifications to your plugins or themes — for that, you’ll use the functions.php file.

There are also some hard-coded aspects of WordPress that you cannot alter, even in wp-config.php — like the location of the themes folder. 

How to protect wp-config.php from security exploits

Your wp-config.php file contains a lot of sensitive information about your site — information you want to keep out of the hands of hackers. Here are a few tips to help secure your wp-config.php file:

1. Install a security plugin

A security plugin for WordPress will automatically add settings to your website that help protect all aspects — including wp-config.php — from hacking attempts.

Jetpack’s WordPress security tool is an inexpensive option that can help keep your site safe from malicious attacks. Jetpack Security includes:

  • Brute force attack protection that stops attacks in their tracks 
  • Downtime monitoring to alert you the second there’s an issue
  • An activity log, so you know if and when suspicious activities occurred
  • Secure authentication to prevent unauthorized access
  • Malware scanning that alerts you if your site has been hacked
  • Spam protection for your pages, posts, and contact forms

Jetpack Security also monitors your site for any changes to core WordPress files, outdated or insecure plugins, and other vulnerabilities so that you can catch them before a hacker finds them and takes advantage.

You can get free vulnerability scanning for your site with Jetpack Protect and easily upgrade Protect to add malware scanning with one-click fixes and our website firewall (WAF) to protect your site around the clock.

2. Deny access to wp-config.php via the .htaccess file

You can use the .htaccess file to help protect wp-config.php. You’ll find this file in your root folder. 

Step 1: Download .htaccess

Using SFTP or cPanel, navigate to the root folder of your website. Right click on .htaccess and select download to download the file to your local computer.

Step 2: Add code to block access to wp-config.php

In a source code or plain text editor, open .htaccess and add the following code:

<files wp-config.php>
order allow,deny
deny from all
</files>

Save your file. Make sure that your program does not include a file extension. If you’re using Notepad or Text Edit, it may add a .txt file extension, which you don’t want. The file should simply be named ‘.htaccess.’ 

Step 3: Upload edited .htaccess back to the root folder

Upload your edited .htaccess file back to your website’s root folder. You’ll be asked if you want to overwrite the existing file. Click Ok.

Now your .htaccess file should block external access to your wp-config.php file.

3. Hide wp-config.php outside the root directory

Since every hacker knows the default location of wp-config.php on a WordPress site, changing the location to a restricted access folder outside the root directory can keep it out of a hacker’s hands. 

This process involves a little extra configuration — you can’t just drag and drop wp-config.php outside the root folder. However, the effort is worth it to add an additional layer of protection to your website. 

In just a few steps, you can secure your wp-config.php file outside the root folder.

Step 1 : Download your current wp-config.php file

Your root folder is where all your WordPress files live, including the wp-config.php file. It may be named ‘public_html’ or ‘www’. If you’re not sure where your root folder or your WordPress directory are, contact your hosting company.

Once you’ve found your root folder and WordPress directory, download your wp-config.php file to your local machine via SFTP or cPanel.

saving the wp-config.php file to your computer via ftp

Step 2 : Create a new directory outside the root folder

Navigate outside of your root directory to the next file folder level up. You should see the name of your root folder as well as several other folders. In this directory, right click and select create directory.

creating a directory via ftp

Give your directory a name that you’ll easily remember as the repository for your wp-config.php file. You can even create multiple nested folders if you like — you’ll just need to remember the names of all of them for Step 4.

Step 3: Upload wp-config.php to your new folder

Upload the wp-config.php file you downloaded earlier into your new folder via SFTP or cPanel.

moving wp-config.php to the new directory

Check your new folder and wp-config.php file permissions and make sure they’re set to 600.

checking file permissions for wp-config.php

changing file permissions to 600

Step 4 : Point WordPress to the new wp-config.php file

You should have a wp-config.php file in your new “secret” directory as well as the original wp-config.php file that’s still in your root directory. In order for WordPress to find and use the correct file, you’ll want to delete all the information in your root directory’s wp-config.php file and replace it with the following code snippet:

<?php
include('/home3/usr/secureconfig/wp-config.php');
?>

Note: Your file path will look different as you’ll be using your individual server’s directory names.

In cPanel, you can open the root directory’s wp-config.php file and edit it directly or you can edit the copy you downloaded to your local machine earlier using a source code editor. For this example, we’ve edited the copy we downloaded earlier using Atom.io.

Save your wp-config.php file and upload it back to your root directory.

moving the wp-config.php file

You’ll be asked if you want to overwrite the file. Click Ok to overwrite the file.

Now WordPress should reference your new wp-config.php file in its secure location outside the root folder.

4. Change the name of your wp-config.php file

Changing the name of your wp-config.php file can also help obscure it from hackers. If you do this, you’ll also need to host this file outside of your root folder. If you’ve already followed the steps in Hide wp-config.php outside the root directory, you can change the name of the wp-config.php file by going through these additional steps:

Step 1: In your secure directory outside the root folder, change the file name of wp-config.php

Navigate to your wp-config.php folder hosted outside your root directory and change the name to something unique, like ‘secret-setup-file.php’ or ‘cheese-sandwich.php’ — it doesn’t really matter.

Step 2: Edit the code in wp-config.php in your root directory to reflect the name change

Now that you’ve changed the name, you’ll need to make sure your root directory copy of wp-config.php is pointing to the right file name. 

Download the root folder copy of wp-config.php to your local computer and edit it with your source code editor of choice. Change the wp-config.php file name to your new file name, then save it.

<?php
include('/home3/usr/secureconfig/cheese-sandwich.php');
?>

Step 3: Upload wp-config.php back to the root directory

You’ll be asked if you want to overwrite the existing file. Click Ok. 

Now WordPress should point to your renamed configuration file. 

wp-config.php edits for better WordPress performance

You can use the wp-config.php file to optimize your WordPress settings and improve the performance of your website. Below are seven edits you can make to wp-config.php to reduce database size and load, improve load time for your site, and conserve server space.

1. Clean up image edits

Every time you edit an image in WordPress, a new set of thumbnails and other image sizes are created. When you restore an original image, those edits are not deleted. This can lead to cluttered media folders. If you want to make sure that only one set of image edits exist on your server and that, when you restore the original, the edits are removed, you can use the following code:

define( 'IMAGE_EDIT_OVERWRITE', true );

2. Repair your database

If your site is running slowly, experiencing errors, and you suspect that your database is corrupt and needs to be repaired, you can enable automatic database repair by using WP_ALLOW_REPAIR and setting the value to ‘true.’

define( ‘WP_ALLOW_REPAIR’, true );

Make sure to disable this feature once the database issue is solved. This script can also be found in the repair.php file: {$your_site}/wp-admin/maint/repair.php.

3. Manage post revision settings

While you’re editing a post, WordPress auto-saves your revisions every 60 seconds by default. If you want longer delays between saves or you’d like more frequent saving intervals, you can modify the auto-save interval. 

define( 'AUTOSAVE_INTERVAL', 60 ); // Seconds

WordPress doesn’t have a limit on the number of post revisions that are saved, so if you’d like to reduce the load that post revisions have on your database, you can specify the maximum number or disable the saving of revisions entirely.

Specify maximum number of post revisions

define( 'WP_POST_REVISIONS', 3 );

Disable post revisions

define( 'WP_POST_REVISIONS', false );

4. Manage trash settings

By default, WordPress permanently deletes items in the trash after they have been there for 30 days. If you want to change that frequency, you can use the following code and set the number to the frequency you want.

define( 'EMPTY_TRASH_DAYS', 30 ); // 30 days

You can also disable the trash from being emptied by setting the number of days to zero.

define( 'EMPTY_TRASH_DAYS', 0 ); // Zero days

Note: If you disable the trash being emptied, WordPress won’t ask for confirmation when someone clicks on Delete Permanently. Use this setting with caution!

5. Adjust cron settings

WordPress uses WP-Cron for scheduling time-sensitive tasks like checking for updates and publishing scheduled posts.

If scheduled posts are not being published or other cron jobs are failing to be completed on your site, you might want to try using alternative cron. When ALTERNATE_WP_CRON is set to ‘true,’ visitors’ browsers are redirected to a new connection while cron continues to run in the dropped connection. 

define( 'ALTERNATE_WP_CRON', true );

Note: Since this method depends on a non-native WordPress service, there are some risks involved.

You can also change the intervals at which cron processes can run or disable cron entirely.

Disable cron

define( 'DISABLE_WP_CRON', true );

Cron timeout

define( 'WP_CRON_LOCK_TIMEOUT', 60 );

6. Increase memory allocated to PHP

If you have plugins or themes that use a lot of PHP resources, you may be confronted with the message, “Allowed memory size of xxxxxx bytes exhausted.” Some themes and plugins may even specify a PHP memory limit minimum to be able to use their software or specific features of their software (like importing demo data). 

WordPress will, by default, attempt to increase PHP memory limits to 40MB for single sites and 60MB for multisite installations, but you may need to set your limit higher. Sometimes, your PHP memory limit is set by your host and while some hosts allow you to edit your PHP memory limit, others do not.

If your host allows you to increase your PHP memory limit, you can add the following code to your wp-config.php file and replace ‘96M’ with the amount of memory you need (remember to use M and not MB after the number):

define( 'WP_MEMORY_LIMIT', '96M' );

This setting increases PHP Memory only for WordPress, not other applications. 

Tasks in the WordPress admin area require a lot more memory than activity on the front end of your website. You can increase your admin area memory by defining WP_MAX_MEMORY_LIMIT. 

define( 'WP_MAX_MEMORY_LIMIT', '256M' );

Note: Put this code before the wp-settings.php inclusion in your wp-config.php file.

7. Enable/disable Cache

Some caching plugins use the advanced-cache.php file and activate WP_CACHE in your wp-config.php file for you. Sometimes you may need to add it manually by adding the following:

define( 'WP_CACHE', true );

Or you may want to disable caching. In that case, replace ‘true’ in the above statement with ‘false.’

define( 'WP_CACHE', false );

wp-config.php edits for better WordPress security

You can use wp-config.php to manage the security of your WordPress site by blocking external URL requests, requiring SSL for admins, moving WordPress core file and folder locations, overriding default file permissions with more restrictive permissions settings, and more. If you’re interested in using wp-config.php to better secure your website, check out the seven tips below: 

1. Define a custom table_prefix

The default prefix for WordPress database tables is ‘wp_’ but you can use any prefix you like with the following code:

$table_prefix = 'customprefix_'; 

Replace ‘customprefix_’ with your text of choice, but only use numbers, letters, and underscores — no special characters.

Note: If you’re changing the table prefix in an existing install of WordPress, you’ll also need to update your table prefixes in your database, run a search and replace for any references to the previous table prefix, and replace them with the new one.

2. Require SSL for admin and logins

If you want to keep admin login information secure, you can use ‘FORCE_SSL_ADMIN’ so that passwords and cookies are always sent over SSL. Set ‘FORCE_SSL_ADMIN’ to ‘true’ with the following code in wp-config.php:

define( 'FORCE_SSL_ADMIN', true );

Note: You’ll also need to have SSL configured on your server before your site will work correctly with FORCE_SSL_ADMIN set to true.

3. Block external URL requests

For added security, you can prevent external URL requests from your server by defining ‘WP_HTTP_BLOCK_EXTERNAL’ as ‘true’. With this constant enabled, only your website and localhost will be able to make requests. 

define( 'WP_HTTP_BLOCK_EXTERNAL', true );

If you want to make an exception for specific hosts, you can define WP_ACCESSIBLE_HOSTS with a list of comma separated host names. If you want to allow all subdomains of a host, prefix the domain name with ‘*.’ (e.g. ‘*.wordpress.org’). and this will only allow localhost and your blog to make requests. 

For example, if you want to make an exception for Google Fonts and all subdomains of WordPress.org, you would add the following to wp-config.php:

define( 'WP_ACCESSIBLE_HOSTS', 'fonts.googleapis.com,*.wordpress.org' );

4. Disable the plugin and theme file editor

By default, WordPress site admins have access to the plugin and theme file editor feature in the WordPress dashboard. This can be a security risk. An admin that doesn’t have a good understanding of how to (and how NOT to) edit these files could attempt to make edits that break your site. A disgruntled admin may intentionally sabotage these files, or a hacker may get access to the admin interface and attempt to edit core files through the plugin and theme file editor.

To disable the plugin and theme file editor define ‘DISALLOW_FILE_EDIT’ as ‘true.’

define( 'DISALLOW_FILE_EDIT', true );

Note: Some plugins may check user capabilities with “current_user_can(‘edit_plugins’)”. If you have plugins installed that use this function, they may not work correctly when ‘DISALLOW_FILE_EDIT’ is set to ‘true’. If you define ‘DISALLOW_FILE_EDIT’ as ‘true’ and you experience issues with a plugin afterward, then this function in the plugin code may be the culprit.

5. Disable plugin and theme updates and installations

If you want to block users from being able to update or install plugins and themes from the WordPress admin area, you can set ‘DISALLOW_FILE_MODS’ to ‘true.’ This will also disable the plugin and theme file editor.

define( 'DISALLOW_FILE_MODS', true );

6. Move core WordPress folders

Keeping core WordPress folders in custom locations can help secure your site against hackers. Especially if hackers are using automated scripts to find the default names of certain files and folders, changing their location can protect your site against these types of attacks.

Move the wp-content folder

Your wp-content directory contains your themes, plugins, and uploads. You can move this outside of the WordPress directory by setting WP_CONTENT_DIR to the full local path of the directory or to the full URL. 

File path

define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/blog/wp-content' );

URL

define( 'WP_CONTENT_URL', 'http://example/blog/wp-content' );

Note: Do not include the trailing ‘/’ in the file path.

Move the plugins folder

You can protect your plugins by moving the folder location and using the following options to define the path to your new folder:

Set ‘WP_PLUGIN_DIR’ to the full local directory path. 

define( 'WP_PLUGIN_DIR', dirname(__FILE__) . '/blog/wp-content/secureplugins/plugins' );

Set ‘WP_PLUGIN_URL’ to the full directory URL.

define( 'WP_PLUGIN_URL', 'http://example/blog/wp-content/secureplugins/plugins' );

If you encounter compatibility issues with plugins, you can set ‘PLUGINDIR’ to the full local directory path.

define( 'PLUGINDIR', dirname(__FILE__) . '/blog/wp-content/secureplugins/plugins' );

Note: Do not include the trailing ‘/’ in the file paths.

Move the uploads folder

Moving your uploads folder is a great way to help protect against scripts that may attempt to upload content directly to the default WordPress uploads folder file path. Use the ‘UPLOADS’ constant to define your path to the uploads folder.

define( 'UPLOADS', 'blog/wp-content/secureuploads/uploads' );

Note: use a relative path to your uploads folder without the leading ‘/.’

7. Override default file permissions

In some cases you might need to adjust file permissions to override default file permissions set either by WordPress or your host. While you could change file permissions individually via SFTP or cPanel, you can also override them en masse by using wp-config.php. You may want to use more restrictive permissions for some files and folders and less restrictive permissions for others, depending on what your objectives are. 

To override a file permission, you’ll use the ‘FS_CHMOD_FILE’ constant. To override a directory permission, you’ll use ‘FS_CHMOD_DIR.’

File

define( 'FS_CHMOD_FILE', ( 0644 & ~ umask() ) );

Directory

define( 'FS_CHMOD_DIR', ( 0755 & ~ umask() ) );

Example to provide setgid (group permissions):

define( 'FS_CHMOD_DIR', ( 02755 & ~umask() ) );

Note:0755′ and ‘02755‘ are octal values and must be prefixed with a ‘0’. 

Advanced wp-config.php features for developers

Beyond security and site optimization, developers can use wp-config.php to add other custom settings to WordPress environments. Below are just a few features to consider using in wp-config.php:

1. Define WordPress URL

The WP_SITEURL constant lets you define the address where your WordPress core files are located. You should include http:// or https://, the root domain, and the subfolder(s) that house your WordPress core files. Don’t include the trailing “/” at the end of the URL, however. 

define( 'WP_SITEURL', 'http://yoursite.com/wordpress' );

When you set the WP_SITEURL address in wp-config.php, the value for ‘siteurl’ in the database will be overridden. Since WP_SITEURL only takes precedence over the ‘siteurl’ value in the database, rather than actually overwriting it, if you delete the WP_SITEURL code in your wp-config.php file, the original database value for ‘siteurl’ will be used. 

You can also dynamically set the site url based on server host or server name.

Server host:

define( 'WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress' );

Server name:

define( 'WP_SITEURL', 'http://' . $_SERVER['SERVER_NAME'] . '/path/to/wordpress' );

Note: It may be safer to use SERVER_NAME than HTTP_HOST. Using HTTP_HOST may allow for file inclusion vulnerabilities. Also, if your server is using Apache and is configured as UseCanonicalName “on”, SERVER_NAME isn’t set dynamically and is instead set by the server configuration. In this case you would want to use SERVER_NAME instead of HTTP_HOST.

2. Define home URL

Your home URL is the url you use to get to the front page of your site. Normally your home URL would be your root domain (e.g. https://mysite.com) even if you install WordPress in a subdirectory. 

If you’d prefer to include your subdirectory as part of your home URL, you can use WP_HOME to override the wp_options table value for home. It won’t change it in the database, so if you remove this line from wp-config.php, your site home URL will revert to the value in the wp_options table.

define( ‘WP_HOME’, ‘https://mysite.com/wordpress’ );

You’ll also need to add the following code to index.php in your site’s root directory:

define( 'WP_HOME', 'https://mysite.com' );

Like with ‘SERVER_NAME’ and ‘SERVER_HOST,’ you can also dynamically set ‘WP_HOME.’ Use $_SERVER[‘HTTP_HOST’] between http:// or https:// and your file path to WordPress (without the root domain) as follows:

define( 'WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress' );

3. Set cookie domain

If you have a non-standard domain setup, you may want to specify your cookie domain using the ‘COOKIE_DOMAIN’ constant. Use cases for this include: 

Serving static content from a subdomain. If you’re serving static content from a subdomain but want to set the cookie domain to the URL where your dynamic content lives, use the following:

define( 'COOKIE_DOMAIN', 'www.mysite.com' );

Note: You don’t need to include the http:// or https:// before the domain name.

Running a multisite network. If you’re running a multisite network in subfolders on a domain and are having problems with cookies (e.g. getting the error ‘Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.’), you can make sure that cookies belong to the domains they’re requested from and not coming from a single domain by setting COOKIE_DOMAIN to an empty value.

define( 'COOKIE_DOMAIN', '' );

4. Enable multisite abilities

WordPress does not come with multisite capabilities enabled automatically. Most WordPress installations won’t need that feature. But if you do need it, you can easily enable it by using the ‘WP_ALLOW_MULTISITE’ constant. 

define( 'WP_ALLOW_MULTISITE', true );

5. Redirect nonexistent subdomains or folders

While you could let visitors land on your default 404 page when content is not found, it might be a better user experience to direct them to a custom page. You can do this easily through wp-config.php using the ‘NOBLOGREDIRECT’ constant. 

define( 'NOBLOGREDIRECT', 'https://mysite.com/custompage' );

6. Do not upgrade global tables

If you have a site with large global tables or are sharing user tables between multiple WordPress installations (forum and eCommerce sites may fall into these categories), you can prevent WordPress from doing resource intensive queries against global tables during the upgrade process by setting ‘DO_NOT_UPGRADE_GLOBAL_TABLES’ to ‘true.’ 

 define( 'DO_NOT_UPGRADE_GLOBAL_TABLES', true );

7. Manage auto-update settings

You may want to disable auto-updates of themes, plugins, and WordPress core — especially if you’re in the middle of testing a development site or troubleshooting an issue. You may also want to choose whether WordPress core updates automatically only for minor updates, for all new version releases, or not at all. 

Disable auto-updates

To disable all automatic updates entirely, set ‘AUTOMATIC_UPDATER_DISABLED’ to ‘true.’

define( 'AUTOMATIC_UPDATER_DISABLED', true );

Disable WordPress core updates

You can set the ‘WP_AUTO_UPDATE_CORE’ constant to allow automatic updates of all version releases, only minor updates, or disable all automatic core updates.

Disable all core updates

define( 'WP_AUTO_UPDATE_CORE', false );

 Enable all core updates

 define( 'WP_AUTO_UPDATE_CORE', true );

Enable core updates for minor releases

define( 'WP_AUTO_UPDATE_CORE', 'minor' );

8. Define WordPress upgrade constants

If you’re having trouble upgrading WordPress, you might need to define some additional WordPress upgrade constants to get to the root of your problem. Try to use as few of these constants as possible to solve your issue.

The two most common reasons that you might need to define these constants in wp-config.php are:

  • Your host is using symlinks in your installation. If this is the case, you might need to define path-related constants like FTP_BASE, FTP_CONTENT_DIR, and FTP_PLUGIN_DIR. 
  • Your PHP installation uses an FTP extension that’s incompatible with certain FTP servers. This is a rare situation, but if you find yourself dealing with this, you might need to define FS_METHOD to ‘ftpsockets.’

Below is a list of valid constants and sample code for WordPress updates:

FS_METHOD This forces the file system method. In order of preference, it should be set to: direct, ssh2, ftpext, or ftpsockets. Only change this if you’re having update issues. If changing it does not solve the problem, you should change it back to its original value or remove it. If other methods fail, ‘ftpsockets’ will usually work. define( ‘FS_METHOD’, ‘ftpext’ );
FTP_BASE The full path to your WordPress installation folder (ABSPATH). define( ‘FTP_BASE’, ‘/path/to/wordpress/’ ); 
FTP_CONTENT_DIR The full path to your wp-content folder. define( ‘FTP_CONTENT_DIR’, ‘/path/to/wordpress/wp-content/’ );
FTP_PLUGIN_DIR The full path to your plugins folder. define( ‘FTP_PLUGIN_DIR ‘, ‘/path/to/wordpress/wp-content/plugins/’ );
FTP_PUBKEY The full path to your SSH public key. define( ‘FTP_PUBKEY’, ‘/home/username/.ssh/id_rsa.pub’ );
FTP_PRIKEY The full path to your SSH private key. define( ‘FTP_PRIKEY’, ‘/home/username/.ssh/id_rsa’ );
FTP_USER Defines either FTP username  or SSH username. While these are often the same, they may be different. Use the FTP username if you’re updating by FTP and SSH username if you’re updating via SSH. define( ‘FTP_USER’, ‘username’ );
FTP_PASS The password for the username defined with FTP_USER. You don’t need to include this if you’re using SSH public key authentication. define( ‘FTP_PASS’, ‘password’ );
FTP_HOST The hostname for your SSH/FTP server. Some configurations should use ‘localhost’ as the ‘FTP_HOST’ value to avoid 503 errors when updating plugins or WordPress core. define( ‘FTP_HOST’, ‘ftp.mysite.com’ );
FTP_SSL This setting applies to configuring “Secure FTP,” not SSH SFTP. Set this to ‘true’ for an SSL connection only if supported by the underlying transport. This may not be available on all servers. SFTP:define( ‘FTP_SSL’, true );FTP:define( ‘FTP_SSL’, false );

9. Create custom user and usermeta tables

The constants ‘CUSTOM_USER_TABLE’ and ‘CUSTOM_USER_META_TABLE’ are used to assign custom tables for storing user data. These settings are best implemented when initially setting up WordPress.

define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' );
define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' );

Note: If you’re running a multisite installation of WordPress, a usermeta table and corresponding permissions is created for the database of each WordPress instance, even if you manually define ‘CUSTOM_USER_META_TABLE’. Permissions are added for the first user only, so you’ll need to manage user permissions for each site using a custom function or plugin, otherwise you’ll experience login issues.

Ensuring admin access with custom user and usermeta tables during multisite setup:

  1. After creating your first site and adding your custom user and usermeta tables, copy the wp-config.php file to your next instance and change the $table_prefix variable. If the first site uses ‘my_usermeta’, your second site should use something different (e.g. ‘site2_usermeta’).
  2. Use a different email address for this next instance than you used for your original install. 
  3. When you’ve completed setup, log in with the auto-generated admin account and password. 
  4. Promote the account you want to use as an admin to the administrator level and then log out of your WordPress admin. 
  5. Log back in with your new admin account and delete the auto-generated account.

10. Save queries for analysis

If you perform and analyze database queries and need to save them for later examination, you can use the ‘SAVEQUERIES’ constant in wp-config.php. The queries are saved to an array which can be displayed using code in your footer.php file. The function will save your queries, what function called them, and the length of time the queries took to execute.

This operation may slow down your site so you should turn this feature off unless you are actively debugging.

Add the following to wp-config.php:

define( 'SAVEQUERIES', true );

In footer.php (in your theme folder), add this code:

<?php
if ( current_user_can( 'administrator' ) ) {
    global $wpdb;
    echo "<pre>";
    print_r( $wpdb->queries );
    echo "</pre>";
}
?>

11. Configure debugging and error logging

Remember the White Screen of Death? Well, following the release of WordPress 5.2, instead of the dreaded blank, white screen, you’ll now see an error message that says “The site is experiencing technical difficulties. Please check your site admin email inbox for instructions.” when a fatal error occurs.

Of course, if there’s a fatal error, you’ll want to enable debugging and error logging so you can troubleshoot the issue. To do this you’ll want to use the ‘WP_DEBUG’ constant and set it to ‘true’ (the default value is ‘false’).

define( 'WP_DEBUG', true );

Setting ‘WP_DEBUG’ to ‘true’ will allow database errors to print, and raises error reporting levels so that you’ll see warnings when deprecated files or functions are being used. 

Before you can print these errors, however, you’ll need to disable recovery mode by setting ‘WP_DISABLE_FATAL_ERROR_HANDLER’ to ‘true’ and enable ‘WP_DEBUG_DISPLAY’. 

define( 'WP_DISABLE_FATAL_ERROR_HANDLER', true );   // 5.2 and later 
define( 'WP_DEBUG_DISPLAY', true );

You can opt not to log the errors and instead just print them on the screen, but you should enable these settings on a development or staging site so as not to print errors visible to the public on your live site. If your settings in your php.ini file are already set to log errors rather than display them, you can override that with the following in wp-config.php:

@ini_set( 'log_errors', 'Off' );
@ini_set( 'display_errors', 'On' );
define( 'WP_DEBUG_LOG', false );

If php.ini is not set to log errors and you want to enable error logging, you’ll need to do a bit more work. 

The default error log and display settings can be found in your php.ini file. In some cases, you may not have access to this file or your hosting company may use user.ini or some other naming convention. If you don’t have access to this file, ask your hosting company to make these changes for you.

Recommended php.ini error settings:

error_reporting = 4339 
display_errors = Off
display_startup_errors = Off
log_errors = On
error_log = /home/mysite.com/logs/php_error.log
log_errors_max_len = 1024
ignore_repeated_errors = On
ignore_repeated_source = Off
html_errors = Off

If you turn on error logging, remember to delete the file afterwards, as it will often be in a publicly accessible location, where anyone could gain access to your log.

You can also use wp-config.php to turn PHP error_logging on and log them to a file you specify. Make sure WP_DEBUG is defined to true and you place the following above any require_once or include commands:

@ini_set( 'log_errors', 'On' );
@ini_set( 'display_errors', 'Off' );
@ini_set( 'error_log', '/home/mysite.com/logs/php_error.log' );
/* That's all, stop editing! Happy blogging. */

For more examples of error logging techniques you can check out Mike Little’s suggestions on wp-hackers’ email list or the Manchester WordPress User Group.

There are a few important things to keep in mind when implementing debugging and logging settings:

  1. If ‘WP_DEBUG’ is set to ‘false’, ‘WP_DEBUG_DISPLAY’ and ‘WP_DEBUG_LOG’ will not work. 
  2. If ‘WP_DEBUG’ is set to ‘true’, the other constants will only be active if they’re also set to ‘true’. This includes directives in your php.ini file — not just statements in wp-config.php. So if php.ini sets (‘display_errors’ = ‘Off’); but define( ‘WP_DEBUG_DISPLAY’, true); is set in your wp-config.php file, errors will not be displayed because your PHP configured behavior will take precedence.
  3. To ensure your directives work as intended, you should explicitly define both php.ini settings and their corresponding wp-config.php settings.

For your public, production WordPress installation, you might consider placing the following in your wp-config.php file, even though it may be partly redundant:

@ini_set( 'log_errors', 'On' );
@ini_set( 'display_errors', 'Off' );
define( 'WP_DISABLE_FATAL_ERROR_HANDLER', false );   // 5.2 and later
define( 'WP_DEBUG', false );
define( 'WP_DEBUG_LOG', false );
define( 'WP_DEBUG_DISPLAY', false );

Note: If you’re using the default debug log file in its default location of /wp-content/debug.log, you’ll want to limit the file access to SFTP only. Set the log file permissions to 600 and add the following to the .htaccess file in your root directory:

<Files debug.log>
    Order allow,deny
    Deny from all
</Files>

12. Define the WordPress environment type

If you’re setting up local, development, or staging sites, it can be useful to define ‘WP_ENVIRONMENT_TYPE’. When this constant is not defined, the default environment type is production. The allowed values are: local, development, staging, and production.

define( 'WP_ENVIRONMENT_TYPE', 'staging' );

Note: When ‘WP_ENVIRONMENT_TYPE’ is set to ‘development,’ WP_DEBUG will automatically be set to ‘true’ if it isn’t already defined in wp-config.php.

13. Debug scripts

If you’re troubleshooting issues with JavaScript and CSS, you can use the SCRIPT_DEBUG constant to force WordPress to use the development versions of scripts and stylesheets. The files in wp-includes/js, wp-includes/css, wp-admin/js, and wp-admin/css will be loaded instead of the minified versions. To view these development versions, set ‘SCRIPT_DEBUG’ to ‘true.’

define( 'SCRIPT_DEBUG', true );

14. Disable JavaScript concatenation

In WordPress, JavaScript files are sequenced to speed up the load time of admin screens. If you’re getting JavaScript errors in the WordPress admin area, you can disable script concatenation by setting ‘CONCATENATE_SCRIPTS’ to ‘false.’

define( 'CONCATENATE_SCRIPTS', false );

Is this the ultimate guide to wp-config.php?

While this article is quite extensive and covers everything from the basics of how to locate, access, and edit wp-config.php, it is by no means exhaustive. How you set up your wp-config.php file will be specific to your needs, your server environment, and personal preferences. If you have additional questions about ways that you can use the wp-config.php file, you can refer to WordPress.org’s support documentation. We’ve also included some answers to frequently asked questions below.

wp-config.php FAQS

What if I can’t find my wp-config.php location?

While your wp-config.php file is normally located in the root folder of your WordPress installation, it may be located somewhere else. You’re more likely to encounter this if you’re taking over a WordPress site from a previous developer or if your hosting company automatically installs WordPress for you. If you’re having trouble finding your wp-config.php file, you can do a search in your SFTP program or in cPanel.

Filezilla

If you’re using Filezilla to access your site via SFTP, you can click on the binoculars icon at the top to perform a file search. Search ‘wp-config.php’ in the top-most folder you have access to in case wp-config.php is located in a folder outside the root directory. It may take several minutes for results to appear, as you’ll be searching all the folders on your server.

search form in Filezilla

cPanel

Searching for wp-config.php in cPanel is pretty straightforward. In your host’s cPanel, click File Manager under Files.

You’ll be taken to your file tree on your server and at the top right of the screen will be a search field. You can use the dropdown selector at the left to choose whether you want to search all files or just a specific directory. Since you don’t know where wp-config.php is, it’s probably best to search all directories.

Enter ‘wp-config.php’ in the search field and click Go.

search form in cpanel

If you still can’t find wp-config.php, it may be that its folder doesn’t have the correct permissions set for you to be able to access it. In this case, contact your hosting company for assistance.

What if my wp-config.php file is not writable?

If you see an error about missing write permissions for wp-config.php in your WordPress dashboard, it’s likely due to a plugin that needs write access to wp-config.php. Some plugins require this type of access to add code that’s required for the plugin to work. However, some hosts may implement strict permissions on wp-config.php for security reasons that also deny write access to these plugins. 

If your host allows you to make changes to these settings, you should be able to change your file and folder permissions via SFTP or cPanel.

SFTP

For this example, we’re using Filezilla.

1. Connect to your server via SFTP.

2. Find your wp-config.php file. It’s located in the root folder of your WordPress installation by default, but may be located somewhere else. 

3. Right click on your wp-config.php file and click File Permissions.

editing file permissions

Make sure the file permissions are set to 640 or 644.

setting file permissions to 644

If wp-config.php is in a folder outside the root folder, double-check that the folder permissions are set to 750 or 755.

setting file permissions to 755

Note: Some hosting platforms may require you to use different permissions values. For files, you can try 664 and 666. For folders, try 775. 

If changing the file permissions does not solve your issue of granting write access, it’s likely that the file ownership settings are to blame and you’ll need to contact your hosting provider in order to make any changes.

Read more about WordPress file permissions.

Can plugins edit my wp-config.php file?

If your folder and file permissions are set to allow write access (750, 755, or 775 for folders; 640, 644, 664, or 666 for files), then plugins should be able to write to wp-config.php. If you want to disable plugins from being able to write to your wp-config.php file, you can set stricter file permissions of 440 or 400. This will also prevent other users on your server from reading wp-config.php.

What is wp-config-sample.php?

When you initially download WordPress, there’s no wp-config.php file included. This file is usually set up during the install process or can be manually configured. The wp-config-sample.php file is included with WordPress so that users have a template to use when manually configuring wp-config.php as well as also having a backup “clean slate” template to work from if something should happen to your original wp-config.php file you created. 

wp-config-sample.php includes all the basic constants and placeholder values required to set up WordPress as well as commented-out explanations of sections within the file that help users understand where to place certain information.

wp-config-sample.php content:

<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the installation.
 * You don't have to use the web site, you can copy this file to "wp-config.php"
 * and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * Database settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://wordpress.org/support/article/editing-wp-config-php/
 *
 * @package WordPress
 */
 
// ** Database settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );
 
/** Database username */
define( 'DB_USER', 'username_here' );
 
/** Database password */
define( 'DB_PASSWORD', 'password_here' );
 
/** Database hostname */
define( 'DB_HOST', 'localhost' );
 
/** Database charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
 
/** The database collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
 
/**#@+
 * Authentication unique keys and salts.
 *
 * Change these to different unique phrases! You can generate these using
 * the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}.
 *
 * You can change these at any point in time to invalidate all existing cookies.
 * This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
define( 'NONCE_KEY',        'put your unique phrase here' );
define( 'AUTH_SALT',        'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
define( 'NONCE_SALT',       'put your unique phrase here' );
 
/**#@-*/
 
/**
 * WordPress database table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';
 
/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the documentation.
 *
 * @link https://wordpress.org/support/article/debugging-in-wordpress/
 */
define( 'WP_DEBUG', false );
 
/* Add any custom values between this line and the "stop editing" line. */
 
 
 
/* That's all, stop editing! Happy publishing. */
 
/** 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';

This entry was posted in Learn. Bookmark the permalink.


Rob Pugh profile

Rob Pugh

Rob is the Marketing Lead for Jetpack. He has worked in marketing and product development for more than 15 years, primarily at Automattic, Mailchimp, and UPS. Since receiving a Master of Science in Marketing Degree from Johns Hopkins University, he’s focused on delivering products that delight people and solve real problems.

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site.


Get up to 51% off your first year.

Compare plans

Is your boss breathing down your neck, telling you to edit the wp-config.php file for “security reasons”?

Is editing wp-config.php turning out to be way too complicated without a security team?

We’ve all been there.

You’ve probably heard that it can be dangerous to edit a WordPress core file too.

So, how do you edit the wp-config file safely?

This article is all about:

  • How to find the wp-config.php file;
  • How to edit it;
  • And what kind of edits you can make…

To level up your WordPress website’s security.

Also, there’s going to be a section on all the different things you can do to improve your website security by editing one PHP file.

This is going to be super actionable, so let’s dive right into it.

migrate wordpress site

Where is WP-Config.php Located?

The wp-config.php file is located in the root folder of your WordPress website. You can find it using two different methods:

  • Using cPanel
  • Using an FTP Client

Once you locate the file in the root directory, you can download wp-config and edit it using a text editor like Notepad. Or you can right-click the file and edit the file inside cPanel directly.

If you have access to the cPanel directly, then it’s a good idea to use that approach. But, if you are working on a client’s website and:

  • You only have access to the FTP credentials
  • Or the managed WordPress hosting that you are using doesn’t provide cPanel,

Then that works just as well.

> Pro Tip: Before we start editing the wp-config.php file, you should know that this is a core WordPress file. In other words, if you mess something up, you will end up breaking your site. So, just take the time to use a WordPress backup plugin first. We highly recommend using BlogVault to take a backup.

Let’s give you a walkthrough of how you can find the wp-config file:

Note: Neither of these methods is totally safe. We recommend using a precaution before doing this, but we’ll talk more about that later.

Method 1: How do I access WP-Config.php without FTP?

The cPanel is your website’s control panel that you can access through your web hosting dashboard.

Step 1: Log into your hosting account.

Step 2: Go to cPanel.

Step 3: Choose, ‘File Manager.’

Find WP-Config.php file through cpanel

You will see a number of files and folders populated on the page.

Step 4: Head over to the ‘public_html’ folder:

Open Public_HTML folder to find WP-Confg.php file

You will find the wp-config.php in this folder.

Method 2: How do I Use FTP to find wp-config.php

If you don’t have access to cPanel you can use an FTP client to do it instead.

We recommend using FileZilla.

Time to use FTP and get down to business:

Step1: Find your FTP credentials. You can find your FTP credentials in your web host dashboard. If you can’t find it, contact your web host and request for your credentials.

Step 2: Launch Filezilla and enter your FTP credentials – the hostname, username, and password – and click on Connect.

ftp credentials

Step 3: Once a connection is successfully established, you should see the folder ‘public_html’. Go inside the folder.

Find WP-Config.php using FTP

You will find the wp-config file in this root folder.

And there you have it! You have found the wp-config.php file.

Time for the much-awaited wp-config.php download!

P.S. – In case you don’t find your wp-config file, don’t worry! You can create one. Let’s take a look at how to do this.

Pro Tip: How Do I Create a WP-Config.php File?

Is the wp-config.php missing from your WordPress installation?

It’s quite possible that you might not find a wp-config.php file at all.

No need to stress.

Just in case you don’t see the wp-config.php file, just rename the “wp-config-sample.php” file to “wp-config” and that will serve the same purpose.

You can do this right inside cPanel.

rename file in file manager

Just click the file to select it and then click on ‘Rename’ in the toolbar to edit the file name.

You can also download the file, edit in on your PC, change the name when you save it, and then upload the new file.

Warning: Remember how we said that editing it directly in cPanel or using FTP on your live site is a very bad idea? Unless you know exactly what you are doing, editing a core file can completely wreck your site.

What can you do to edit the wp-config.php file safely?

First of all, take a backup of your entire site. This way, if things go south, you can just hit restore. Even so, we highly recommend using a staging site for any changes that you might make here.

Our backup plugin BlogVault gives you an easy way to backup your site. You also get a FREE staging site to experiment with your WordPress files.

Once you are done, you can click one button and merge the staging site with the live site for instant results.

We’ll dive into editing the wp-config file’s PHP code soon, but first:

What is wp-config.php?

If you want to jump right into editing the code, then click here.

Or, you can read on and learn a lot more about the WordPress file than you originally signed up for!

What is the WP-Config.php file?

The wp-config.php is a configuration file that stores some of your website’s most important settings and configurations. It also contains your website’s database information.

In short: If you don’t have the wp-config file, then your WordPress site won’t be able to establish a database connection.

If there is anything wrong with this WordPress configuration file, WordPress flags the error message:

‘Error in Establishing Database Connection’

This error will show up whenever someone tries to access the site.

A WordPress website is made up of files and a database. WordPress files mostly contain settings and configurations, while the database contains your posts, comments, users, etc.

The wp-config.php file essentially connects the files with the database.

Now, you don’t have to touch this file so long as you are fine with the wp-config.php default settings.

But your wp-config file can come in handy if you want to:

  • Find your database name and database password;
  • Change the database prefix;
  • Move from one web server to another;
  • Switch domain names;
  • Change database settings;
  • Apply WordPress security precautions;
  • Customize functionality and improve performance;

And a LOT more.

We already know where the wp-config file is located. So, let’s go and edit the file!

How to Edit wp-config.php?

WP-config.php location – Discovered? Check!

PHP file – Downloaded? Nope. That’s up next:

Step 1: Select the file and click on download.

download wp config

Step 2: Open it in a text editor like Notepad. Here, you’ll be able to edit it. To edit the file, simply make the changes you require.

This means you can add your own code, edit the existing code, or even delete some of it.

Step 3: Save the changes.

Then, head back to the File Manager and upload it to the public_html folder. You can just overwrite the old file.

Boom!

You just learned how to edit wp-config.php.

upload wp config

Now that you know how to download, edit, and re-upload your wp-config file, we can show you what kind of edits to make.

This is serious stuff, here.

Again, we can’t stress enough that doing this without a backup and a staging site is downright dangerous. Do NOT do that under any circumstances.

What Edits Can You Make to the wp-config File?

When you open a wp-config.php file, you will see something like this:

By the way, if you want to skip the default code and move on with the rest of the article, just click here.

<?php


/**

* The base configuration for WordPress

*

* The wp-config.php creation script uses this file during the

* installation. You don't have to use the web site, you can

* copy this file to "wp-config.php" and fill in the values.

*

* This file contains the following configurations:

*

* * MySQL settings

* * Secret keys

* * Database table prefix

* * ABSPATH

*

* @link https://codex.wordpress.org/Editing_wp-config.php

*

* @package WordPress

*/

// ** MySQL settings ** //

/** The name of the database for WordPress */

define('DB_NAME', 'Database_SAMPLE');

/** MySQL database username */

define('DB_USER', 'Username_SAMPLE');

/** MySQL database password */

define('DB_PASSWORD', 'sample_password');

/** MySQL hostname */

define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */

define( 'DB_CHARSET', 'utf8' );

/** The Database Collate type. Don't change this if in doubt. */

define( 'DB_COLLATE', '' );

/**

* Authentication Unique Keys and Salts.

*

* Change these to different unique phrases!

* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}

* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.

*

* @since 2.6.0

*/

define('AUTH_KEY',                'sample authentication key');

define('SECURE_AUTH_KEY',     'sample authentication key');

define('LOGGED_IN_KEY',           'sample authentication key');

define('NONCE_KEY',               'sample authentication key');

define('AUTH_SALT',               'sample authentication key');

define('SECURE_AUTH_SALT',    'sample authentication key');

define('LOGGED_IN_SALT',      'sample authentication key');

define('NONCE_SALT',              'sample authentication key');

/**

* WordPress Database Table prefix.

*

* You can have multiple installations in one database if you give each

* a unique prefix. Only numbers, letters, and underscores please!

*/

$table_prefix = 'wp_';

/**

* For developers: WordPress debugging mode.

*

* Change this to true to enable the display of notices during development.

* It is strongly recommended that plugin and theme developers use WP_DEBUG

* in their development environments.

*

* For information on other constants that can be used for debugging,

* visit the Codex.

*

* @link https://codex.wordpress.org/Debugging_in_WordPress

*/

define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */

if ( ! defined( 'ABSPATH' ) )

define( 'ABSPATH', dirname( __FILE__ ) . '/' );

/** Sets up WordPress vars and included files. */

require_once ABSPATH . 'wp-settings.php';

Holy cow!

Unless you’re a pro WordPress developer, you’re probably very lost right now.

That’s OK.

The only people who fully understand what all of this means are developers who are familiar with the WordPress codex.

Fun Fact: The WordPress codex is a repository of tags and functions in WordPress used frequently by developers.

Don’t worry if you’re not a pro yet. We’ll help you get through this yet!

Let’s take a look at each element and understand what it means and how you can edit it:

Checkout our latest guide on WordPress Troubleshooting

Moving WP-Content folder

Ever since WordPress version 2.6 you can move your wp-content directory to a different location. The wp-content directory stores all your theme files, plugin files, and images.

So, why would you want to move your wp-content folder?

Hackers target this folder often to inject malware.

By default, this WordPress folder is in the public_html folder, and hackers are well aware of the default settings. If you move this folder to another location, it makes it hard for hackers to find it.

You can change the location of wp-content from the wp-config.php file.

NOTE: Add these new constants above the line where WordPress includes the wp-settings.php:


// Add constant variables above this line

/** Sets up WordPress vars and included files. */

require_once(ABSPATH . 'wp-settings.php');

All you have to do is add a new variable:

Define WP_CONTENT_DIR and change the location of your wp-content folder. Here’s how you can do it:

define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/content/wp-content' );

To change the location of the wp-content URL there is another variable you need to define in the wp-config.

define( 'WP_CONTENT_URL', 'https://blogvault.net/blog/content/wp-content' );

By the way, you need to replace the above URL with your own URL. Swap out blogvault.net with your siteurl.

Moving the Plugin Folder

If you don’t want to change the location of the entire wp-content folder but just want to move the plugins folder then you can do that too.

It’s easy – you do it pretty much the same way as moving the wp-content folder.

For the plugin folder location, you need to define the variable WP_PLUGIN_DIR:

define( ‘WP_PLUGIN_DIR’, $_SERVER[‘DOCUMENT_ROOT’] . ‘/blog/content/wp-content/plugins’ );

You can also change the URL of the plugins folder for the variable WP_PLUGIN_URL using this piece of code:

define( ‘WP_PLUGIN_URL’, ‘http://example/blog/content/wp-content/plugins’);

The problem with changing the location of the plugins folder is that there is another variable that can be used by some plugin developers called PLUGINDIR. You need to change this too. Otherwise, you might end up with some nasty plugin conflicts.

Here’s how you do it:


define( 'PLUGINDIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/content/wp-content/plugins' );

Moving Themes Folder

You can’t move the themes folder in WordPress. Doing so can cause several problems with installed plugins and some plugins may not even work after this change.

This is the default code that defines the path for the themes folder.

$theme_root = WP_CONTENT_DIR . ‘/themes’;

As a workaround, you can register an additional theme directory using register_theme_directory.

NOTE: This is NOT recommended by WordPress experts because changing the theme directory may cause plugin conflicts that are very difficult to resolve.

Moving the Uploads Folder

Any media uploaded to your website is stored in the wp-content/uploads folder by default. You can choose to store it elsewhere by adding this line:

define(‘UPLOADS’, ‘wp-content/myfolder’);

Replace ‘myfolder’ with the name of the folder you want to use.

Add the following lines in the wp-config.php file and save your changes. The first line is a comment line for future reference.


/** Change Media Upload Directory */

define('UPLOADS', ".'media');

Of course, here we are using a folder called “media” to upload our WordPress files. If you want to name it something else, just give it a different name.

WordPress Debug Mode

The next modification you can make to the wp-config file is useful for developers who want to experiment with features and learn about the WordPress software.

You will learn that the default wp-config.php debug settings are disabled on a WordPress site:

define(‘WP_DEBUG’, false);

This means error notifications will not be displayed. If you want to see these errors and debugging messages, you need to change this line to:

define(‘WP_DEBUG’, true);

This is helpful for developers who want to find and fix bugs. (Recommended read: Debugging WordPress)

Configure Error Logging

In the last segment, we learned how to turn on debugging mode.

WP_DEBUG flags errors in the WordPress backend. But the downside is that it also flags errors on the frontend.

If you want errors to be logged, then you will also need to add the following code in your wp-config.php file just below the WP_DEBUG line:

define( ‘WP_DEBUG_LOG’, true );

Change URLs

When you migrate to a new domain or web server, you may need to change your WordPress URLs. You can do this on the dashboard by going to Settings >> General.

change the site url in wordpress admin dashboard

You can also make the change in the wp-config file by adding these two lines:

define(‘WP_HOME’,’http://example.com’);

define(‘WP_SITEURL’,’http://example.com‘);

You can also use a migration plugin to do this on autopilot.

This can come in handy in case you don’t have access to your wp-admin.

Limit and Specify the Number of Post Revisions

WordPress maintains all revisions made to your posts. This can increase the amount of data on your website.

It can eat up web server resources, slow down your website’s speed, and also increase the size of your backup.

Enter in the following code towards the top of the wp-config.php file to limit the number of post revisions:

define(‘WP_POST_REVISIONS’,5 );

This means only up to the last 5 revisions will be stored. The rest will be discarded. You can change ‘5’ to any number you prefer.

Disable the Plugin and Theme Editor

Every office has that one hyper, bubbly coder who likes to fiddle with everything.

No, really. They like to play around with everything.

Disable the plugin and theme editors. You’ll thank us for this later!

Disabling these also extends an additional layer of security if a hacker gains access to a well-privileged user account.

define( ‘DISALLOW_FILE_EDIT’, true );

Heads Up: This is great for security, but make sure that this does not cause any plugins to stop working.

Disable Plugin and Theme Update and Installation

Sometimes, updates can break your site or cause incompatibility issues.

In some cases, plugins and themes may not be compatible with the WordPress version running on your website.

By letting WordPress install them without checking the compatibility, your website could crash.

In cases where there are multiple users working on a site, you might want to disable the option to update or install themes and plugins.

This is also useful for developers and WordPress experts who want to disable file permission for their clients so that they don’t install something without checking if it’s trusted and compatible.

You can disable this feature from appearing on your dashboard by adding this line:

define(‘DISALLOW_FILE_MODS’, true);

To enable the function, you need to change ‘true’ to ‘false’.

You can also enable and disable updates and installs on your website using a security plugin like MalCare. Its website hardening features enable you to do this with just a few clicks. Also you can check out our guide on rollback WordPress plugin.

Modify AutoSave Interval

As you create and revise documents, WordPress automatically saves your edits at regular intervals.

The default interval is 60 seconds.

You can increase or decrease this time by adding this line of code:

define(‘AUTOSAVE_INTERNAL’, 160); //seconds

Disable Post Revisions

In the steps below we’ll show you how to completely turn off WordPress revisions for your pages and posts. Again we’ll be using the WP_POST_REVISIONS setting in your wp-config.php file to make these changes.

Enter in the following code towards the top of the wp-config.php file:

define(‘WP_POST_REVISIONS’, false);

By setting the parameter to ‘false,’ we have effectively disabled post revisions.

Disable Automatic Updates

You can disable automatic updates by adding this line to your wp-config file:

define(‘WP_AUTO_UPDATE_CORE’, false );

To enable it again, you can simply delete this line or change ‘false’ to ‘true’.

Since version 3.7 of WordPress, minor updates were made automatically. Minor updates usually carry security patches that would fix any vulnerabilities present in the WordPress software.

We recommended keeping auto-updates turned on for the minor ones. You can do so by adding this line:

define ( ‘WP_AUTO_UPDATE_CORE’, ‘minor’ );

(Recommended Read: How to Safely Update Your WordPress Site)

Set the Cookie Domain

Cookies are plain text files that are created and stored in the users’ browsers when they visit a website.

Cookies store analytical information on visitor interactions.

Take an ecommerce site for instance – you would definitely want to track a customer’s journey, wouldn’t you?

That’s only one use of a cookie. You can also use cookies for advertising and remarketing.

By default, WordPress uses cookies to manage logged-in user sessions and authentication. It also uses cookies to remember a user’s name and email address if they fill out a comment form. If the cookies get hacked, then essentially, your access credentials could get leaked.

WordPress allows you to set the cookie domain for your WordPress site so that you can set up cookies across domains and subdomains as required.

Here’s the code:

define( ‘COOKIE_DOMAIN’, ‘www.blogvault.net’ );

Enable Multisite / Network Ability

WordPress multisite enables you to create multiple WordPress sites on a single installation of WordPress.

To create a network of sites, you need to add the following line:

define(‘WP_ALLOW_MULTISITE’, true);

That’s pretty much all you need.

Increase the Maximum Upload and PHP Memory Limit

You can increase the maximum upload size and PHP memory limit in WordPress from the wp-config PHP file so that you can upload large files to WordPress.

To edit the memory limit find this line of code:

define(‘WP_MEMORY_LIMIT’, ’32M’);

A PHP memory limit of 128M should be more than enough. So, increase the limit from 32M to 128M using the following line of code:

define(‘WP_MEMORY_LIMIT’, ‘128M’);

Remember to save the file and don’t go overboard with this limit or you may end up crashing your server.

Security Keys

/**

* Authentication Unique Keys and Salts.

*

* Change these to different unique phrases!

* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}

* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.

*

* @since 2.6.0

*/


define('AUTH_KEY',                 'sample authentication key');

define('SECURE_AUTH_KEY',  'sample authentication key');

define('LOGGED_IN_KEY',            'sample authentication key');

define('NONCE_KEY',                'sample authentication key');

define('AUTH_SALT',                'sample authentication key');

define('SECURE_AUTH_SALT','sample authentication key');

define('LOGGED_IN_SALT',      'sample authentication key');

define('NONCE_SALT',               'sample authentication key');

Here, WordPress tells you that you can change these keys to different unique phrases of your own.

Why would you ever need to change these keys?

Let’s take a step back.

Once you login to your WordPress account, you don’t have to keep logging in every time, right? This is because of browser cookies. It stores information needed to log you in automatically.

If stored in plain text, in the event hackers get their hands on this information, they can read it. To safeguard this data, we encrypt it using security keys and salts.

A WordPress Security Key is a password that is made up of random elements. It’s created to be long and complex so that it’s almost impossible for any hacker to figure it out.

Salts add an extra layer of protection to the cookies and security keys. So, even your security key is protected.

In the wp-config file, there are 4 security keys used to sign the cookies for your WordPress site. There are four corresponding salts for each key.

If your WordPress account has been compromised, you need to change these keys.

To do this, you can generate new keys using the online WordPress security key generator. Copy the entire thing and replace the same in your wp-config file.

This will invalidate all cookies stored and force all users to be logged out. They will need to log in again. So anyone logged in to WordPress including a hacker will be logged out.

Security keys and salts don’t need to be remembered. You should just never disclose them or post them online. It’s recommended you change these keys if you suspect a hack or are recovering from one.

Disable Javascript Concatenation

Javascript concatenation combines multiple Javascript files into one. While this is a good thing, the WordPress defaults for JS concatenation are rarely used.

Instead, a speed optimization plugin such as WP Rocket is used to combine multiple JS and CSS scripts to decrease load time.

Now, having multiple scripts working on the same thing can lead to a bunch of errors.

So, here’s how you can disable Javascript concatenation in wp-config.php:

Define CONCATENATE_SCRIPTS constant to false. In wp-config. php use the code:

define(‘CONCATENATE_SCRIPTS’, false);

Simple!

Understand Database Configuration Settings

As you create new users, and publish posts and comments, all the data is stored in your database.

As a site owner, you would normally never need to access this. But there are times where you would need to know your database name, database username, and password.

This information is contained in the wp-config.php file under ‘MySQL settings’:


// ** MySQL settings ** //

/** The name of the database for WordPress */

define('DB_NAME', 'Database_SAMPLE');

/** MySQL database username */

define('DB_USER', 'Username_SAMPLE');

/** MySQL database password */

define('DB_PASSWORD', 'sample_password');

/** MySQL hostname */

define('DB_HOST', 'localhost');

Set DB_Name: The name of your database

Set DB_User: The user who has access to the database

Set DB_Password: Security passcode required to access the database

Set DB_Host: Your database server’s hosting name. In most cases, it’s left as ‘localhost’

This information doesn’t need to be changed in most cases. In the rare event that your WordPress host provider uses alternate ports, you would need to specify it here.

For example, if the port number is 654321, you need to change to:

define(‘DB_HOST’, ‘localhost:654321’);

MySQL Alternate Port

If your host uses an alternate port number for your database you’ll need to change the DB_HOST value in the wp-config.php file to reflect the alternate port provided by your host.

This can happen in a bunch of different ways.

For localhost:

define( ‘DB_HOST’, ‘127.0.0.1:3107’ );

or in some cases:

define( ‘DB_HOST’, ‘localhost:3107’ );

For specified server:

define( ‘DB_HOST’, ‘mysql.example.com:3107’ );

Replace 3107 with whatever port number your host gives you.

MySQL Sockets or Pipes

If your host uses UNIX sockets or pipes, you have to adjust the DB_HOST value in the wp-config.php file accordingly.

This is rare, but here you go:

define( ‘DB_HOST’, ‘127.0.0.1:/var/run/mysqld/mysqld.sock’ );

// or define( ‘DB_HOST’, ‘localhost:/var/run/mysqld/mysqld.sock’ );

// or define( ‘DB_HOST’, ‘example.tld:/var/run/mysqld/mysqld.sock’ );

P.S. – Replace /var/run/mysqld/mysqld.sock with the socket or pipe information provided by your host.

Character Set and Collation

Take a quick look at these next few lines now:


/** Database Charset to use in creating database tables. */

define( 'DB_CHARSET', 'utf8' );

/** The Database Collate type. Don't change this if in doubt. */

define( 'DB_COLLATE', '' );

DB_Charset - A character set (charset) is a collection of characters that might be used by multiple languages.

Consider it a form of coding in which every character of a language (letters, numbers, and symbols) is assigned a unique code or numerical value.

Why is it needed?

The WordPress platform is used all over the world and in various languages. So it needs a character encoding system that can be used to display different languages.

Unicode is one such encoding system wherein every letter, digit or symbol is assigned a numeric value that applies across different languages, programs, and platforms.

The default WordPress settings assign the character set to Unicode (UTF-8) as it supports almost all languages.

You can disable the character set or change it to an encoding system of your choice, but that’s not a very popular choice.

DB_COLLATE – In order for the character set to work, it needs rules for comparing and sorting called collations.

If you leave the settings as NULL or empty, WordPress will automatically fetch the correct collation as assigned by your server.

Many WordPress users choose to enter the default Unicode collation:

define(‘DB_COLLATE’, ‘utf8_general_ci’); // general collation

Change WordPress Database Table Prefix

$table_prefix = ‘wp_’;

Every WordPress website stores the majority of its data in a database such as pages, posts, comments, tags, etc.

There are 11 default database tables, and each one stores different kinds of data. When you install WordPress, the 11 core tables are prefixed by default with ‘wp_’ like wp_comments, wp_posts, wp_options, etc.

Hackers know the default database prefix and this makes it easier for them to locate and break into databases.

To improve the security of your WordPress database, you can change this prefix to something of your choice. It will make it harder for hackers to guess the name of your WordPress database and its tables.

You needn’t edit the wp-config.php file. You can install a plugin like Change DB Prefix to create unpredictable, random table prefixes.

If you wish to edit the WordPress configuration, replace ‘wp_’ with something of your choice:

$table_prefix = ‘tra_’;

Custom User and User Meta Tables

WordPress uses some default tables to store user data and user metadata. Now, the simplest way to set up custom tables is to do it during installation.

You can change the default settings in wp-config.php using the following code:

define( ‘CUSTOM_USER_TABLE’, $table_prefix.’my_users’ );

define( ‘CUSTOM_USER_META_TABLE’, $table_prefix.’my_usermeta’ );

You can use any prefix you want for them.

But here’s the deal: WordPress will still have the original User and User Meta Tables.

Language and Language Directory

The default language for any WordPress installation is English.

Good news, though: WordPress comes with 65 other languages preinstalled!

WordPress v4.0 allows you to change the language from the Admin Dashboard:

general settings wordpress

For WordPress v3.96 and other lower versions, you can change the language file and its location from the wp-config.php file.

Just include these two lines of code:

define( ‘WPLANG’, ‘de_DE’ );

define( ‘WP_LANG_DIR’, dirname(__FILE__) . ‘wordpress/languages’ );

If you don’t have the WP_LANG_DIR defined, then WordPress will look at the wp-content/languages and wp-include/languages for the language (.mo) file.

Save Queries for Analysis

You can save database queries in an array and display that array later on for analyzing.

HEADS UP: This is really advanced stuff. Unless you are a database administrator, do not use this function. Also, even if you are going to use this, make sure that you turn it off after debugging. If you keep this function active throughout, it will slow down your server speed.

Add this line to the wp-config:

define( ‘SAVEQUERIES’, true );

Doing this will create an array of all the database queries executed, what functions they called, and how long they took to execute.

But the catch is:

You will also need to add some code to your theme footer:


<?php

if ( current_user_can( 'administrator' ) ) {

global $wpdb;

echo "<pre>";

print_r( $wpdb->queries );

echo "</pre>";

}

?>

Happy debugging!

Override of Default File Permissions

This is a pretty important one. Once you have your WordPress website installed, you don’t want just anyone editing your files and uploading random files, themes, and plugins.

That is a surefire way to increase your chances of getting hacked.

At the same time, you don’t want to completely shut down your website from being able to write anything new to its files.

You can do this the manual way and keep reading, but there is an easier way to set up the right WordPress file permissions.

Best practices for file permissions (CHMOD or Change Mode permissions) for:

  • .htaccess and wp-config.php: change to 444 (Anyone can read it, but no one can edit it)
  • All other files: change to 644 (Editable only by the owner, but visible to all)
  • WordPress directories and sub-directories: change to 755 (Editable only by the owner, but visible to all)

Add this code to your wp-config.php file:


define( 'FS_CHMOD_DIR', ( 0755 & ~ umask() ) );

define( 'FS_CHMOD_FILE', ( 0644 & ~ umask() ) );

chmod 644 wp-config.php

chmod 644 .htaccess

That should do it!

WordPress Upgrade Constants

WordPress constants are some unique identifiers that help you take action from the backend.

In short: they are PHP constants that help you modify your WordPress website without any input fields.

A typical use for PHP constants is to make WordPress updates more secure. This is usually done so that your site download the update files over a secure connection.

If you want to that’s what you’re looking for, then there are two ways to do it:

  • Use FTP
  • Use SSH

The best part?

You can use WordPress constants in wp-config to resolve any update issues that you might have and do it in a secure way.

Drop this code in your wp-config.php file and replace the default values with whatever you need it to be:


define('FS_METHOD', 'ftpext');

define('FTP_BASE', '/path/to/wordpress/');

define('FTP_CONTENT_DIR', '/path/to/wordpress/wp-content/');

define('FTP_PLUGIN_DIR ', '/path/to/wordpress/wp-content/plugins/');

define('FTP_PUBKEY', '/home/username/.ssh/id_rsa.pub');

define('FTP_PRIKEY', '/home/username/.ssh/id_rsa');

define('FTP_USER', 'username');

define('FTP_PASS', 'password');

define('FTP_HOST', 'ftp.example.org');

define('FTP_SSL', false);

This method is way better than setting auto-upgrades to your WordPress files. Auto-updates sound really nice, but they can completely expose your website.

Not cool!

Using WordPress Crons the Right Way

Cron helps you to keep publishing your posts on a schedule. You can do this even within the WordPress admin dashboard:

wordpress publish button date

But here’s the problem:

Cron in WordPress is not like a typical Linux Cron. WordPress checks for scheduled events each time there is a new page visitor.

So, if you have little website traffic, the cron may never get launched and if your traffic is too high, the cron gets triggered way too often and hogs your server resources.

So, you can do one of three things:

  • Define alternate crons
  • Disable cron altogether
  • Set a cron timeout limit

Using an Alternate Cron

The user’s browser gets a redirect when the cron needs to run, so that they come back to the site immediately. Meanwhile, the cron continues to run in the connection they just dropped.

Using this code will do the trick here:

define( ‘ALTERNATE_WP_CRON’, true );

This is a risky method, though.

Using an alternate cron requires a non-WordPress solution inside WordPress.

But this is a pretty common method to resolve publishing issues with scheduled posts.

Disable Cron Completely

As we said, the WordPress cron can be really unpredictable. There’s no way to tell how it will react when your website traffic surges.

So, disabling it altogether is also a pretty common practice.

Use this code to do it:

define( ‘DISABLE_WP_CRON’, true );

Setting a Cron Timeout Limit

Another way to handle issues with a cron getting triggered too often is to set a timeout limit.

In other words, a cron cannot run more than once in a certain span of time.

For instance:

define( ‘WP_CRON_LOCK_TIMEOUT’, 60 );

This code restricts a cron from running more than once every minute.

Empty Trash

Every time you delete something in WordPress, it doesn’t get automatically deleted. Instead, it gets moved to the Trash Bin.

Now, the Trash Bin will automatically clean itself after a set period of days.

You can change this period in wp-config.php using this code:

define( ‘EMPTY_TRASH_DAYS’, 30 ); // 30 days

You could get rid of the Trash Bin altogether by setting that number to zero.

That way, if you delete something in WordPress – comments, posts, pages, and attachments – it will get deleted permanently without confirmation.

Automatic Database Optimizing

WordPress offers a database repair option. This is amazing news for semi-pro developers – especially if you’ve got little experience handling databases.

The best part?

All you have to do to enable it is to drop one line of code in the wp-config.php file:

define( ‘WP_ALLOW_REPAIR’, true );

Heads Up: Don’t leave this option turned on forever. Only use this to recover or repair a corrupted database and then remove this code. This tiny bit of code can allow users to get access to the backend without having to log in. If there was ever a bait for hackers to rush in – that would be it.

View All Defined Constants

PHP has a function that returns an array of all the currently defined constants with their values.

print_r( @get_defined_constants() );

This is not a super-popular option with most users, but it’s a nice way for database admins to understand what’s going on at a glance.

Require SSL for Admin and Logins

There are cookies that store passwords whenever a WordPress admin tries to log in.

Using FORCE_SSL_ADMIN forces secure logins. Normally, login credentials are communicated in a plaintext file. Forcing the use of SSL for Admin and Logins will encrypt this information so that no one can eavesdrop on it. This way, the admin area is always protected.

define( ‘FORCE_SSL_ADMIN’, true );

This is a very simple way to harden your WordPress security.

Block External URL Requests

You can block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true.

This option is immensely helpful for developers as it only allows the localhost and your blog to make requests.

The constant WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests.

The format of the WP_ACCESSIBLE_HOSTS constant is a CSV of hostnames to allow and wildcard domains that are supported.

For instance: *github.com will allow for all subdomains of wordpress.org to be contacted.

Edit wp-config to include this code:


define( 'WP_HTTP_BLOCK_EXTERNAL', true );

define( 'WP_ACCESSIBLE_HOSTS', 'api.wordpress.org,*.github.com' );

That’s all!

Disable WordPress Auto Updates

How often do you click on the checkbox “Auto-Update WordPress” during the WordPress installation?

Yeah, that’s not a good idea – especially if you have a custom theme installed.

Think about it:

The new update could potentially wreck your site with even a small change in the WordPress core files.

The general rule of thumb is to test it out on a WordPress test site before uploading it to the production site.

Drop this code in the wp- config.php file:

define( ‘AUTOMATIC_UPDATER_DISABLED’, true );

That’ll shut down the auto-update feature.

Disable WordPress Core Updates

You can disable core updates by adding this line to your wp-config file:

define(‘WP_AUTO_UPDATE_CORE’, false );

To enable it again, you can simply delete this line or change ‘false’ to ‘true’.

Since version 3.7 of WordPress, minor updates were made automatically. Minor updates usually carry security patches that would fix any vulnerabilities present in the WordPress software.

We recommended keeping auto-updates turned on for the minor ones. You can do so by adding this line:

define ( ‘WP_AUTO_UPDATE_CORE’, ‘minor’ );

(Recommended Read: How to Safely Update Your WordPress Site)

Clean up Image Edits

You can edit images in WordPress. But every time you edit an image, WordPress saves a copy of the original and the edited version separately.

The result?

Too many copies of the same image on the server.

Edit wp-config and add this line of code:

define( ‘IMAGE_EDIT_OVERWRITE’, true );

This way, only one set of image edits are ever created and when you restore the original, the edits are removed from the server.

Stop Editing

If you see this line of code:

/* That’s all, stop editing! Happy blogging. */

STOP EDITING.

We can’t tell you how many times coders ignore this simple instruction.

You don’t want to go there.

Ever.

This line is crucial to the proper functioning of the wp-config file. Any changes you want to make or add to the file should be done above this line.

The final section of the wp-config file is:

/** Absolute path to the WordPress directory. */

if ( ! defined( ‘ABSPATH’ ) )

define( ‘ABSPATH’, dirname( __FILE__ ) . ‘/’ );

/** Sets up WordPress vars and included files. */

require_once ABSPATH . ‘wp-settings.php’;

It defines an absolute path that is used to set up WordPress vars and included files.

An absolute path is the location of a directory or a file on a computer. So, again, for the love of God – do NOT edit anything here.

What’s Next?

The wp-config file controls critical elements of your WordPress website. So, always remember to take a backup before you edit this file.

While you can make changes and improve your site, you can also make errors and break your site. We suggest editing the file on a staging site. This will ensure any errors you make will not affect your live site.

Even so, as far as possible, we advise configuring settings from the WordPress dashboard.

One of the simplest ways to do this is to use a WordPress staging plugin to set up a staging site and a backup. This is where the BlogVault WordPress Plugin can come in handy.

Try it out now for one-click solutions on:

  1. Migration and Staging
  2. Effective Backups
  3. WordPress security hardening

Phew!

That was a lot of info for one blog post, wasn’t it?

Is there anything that you would like to ask us? Send us a quick tweet and our WordPress experts will help you in any way that we can.

Akshat is the Founder and CEO of BlogVault, MalCare, and WP Remote.
These WordPress plugins, designed for complete website management, allows 100,000+ customers to build and manage high-performance
websites with ease.

Файл wp-config.php является важной составляющей установки WordPress. В этом руководстве мы рассмотрим такой аспект как настройка файла wp-config.php. Созданный в процессе установки WordPress файл содержит параметры для конфигурации базы данных. Образно говоря, этот файл позволяет WordPress установить соединение с базой данных.

Тем не менее, веб-мастер должен знать, как правильно им управлять, чтобы обеспечить безопасность сайта. Без него ваш WordPress сайт не сможет хранить и извлекать данные из базы данных.

В этой статье мы рассмотрим функциональность файла wp-config.php. Мы также покажем вам, как отредактировать файл wp-config.php и задать пользовательские настройки на вашем веб-сайте.

Полная настройка файла wp-config.php

Файл wp-config.php — это файл конфигурации, созданный динамически в процессе установки WordPress. Он хранит информацию о базе данных, такую как имя базы данных, имя пользователя, пароль и хост.

Помимо установления соединения между вашим сайтом WordPress и базой данных, WordPress также использует файл wp-config.php для реализации дополнительных настроек на сайте.

Этот файл хранится в корневой папке вашего сайта. Получить доступ к файлу wp-config.php можно через FTP-клиент, такой как FileZilla, или файловый менеджер вашего веб-хостинга. Пример файла wp-config.php в каталоге /public_html:

wp-config.php файл в корне сайта

Если по каким то причинам вам нужно создать файл wp-config.php вручную, WordPress предоставляет образец файла под названием wp-config-sample.php который так же лежит в корневой папке.

Он содержит всю необходимую информацию, идеально подходящую для начинающих разработчиков под WordPress, которые еще не знакомы с файлом. Помните, что нельзя менять порядок кода, так как это может привести к ошибкам на сайте.

<?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://wordpress.org/support/article/editing-wp-config-php/
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );
/** MySQL database username */
define( 'DB_USER', 'username_here' );
/** MySQL database password */
define( 'DB_PASSWORD', 'password_here' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );
/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
*
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define( 'AUTH_KEY',         'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
define( 'NONCE_KEY',        'put your unique phrase here' );
define( 'AUTH_SALT',        'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
define( 'NONCE_SALT',       'put your unique phrase here' );
/**#@-*/
/**
* WordPress database table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the documentation.
*
* @link https://wordpress.org/support/article/debugging-in-wordpress/
*/
define( 'WP_DEBUG', false );
/* Add any custom values between this line and the "stop editing" line. */
/* That's all, stop editing! Happy publishing. */
/** 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';

WordPress использует константы PHP, которые являются идентификаторами, их нельзя изменить при выполнении скрипта PHP. Эти идентификаторы (константы) определяют настройки базы данных в файле wp-config.php. К каждому параметру прилагаются инструкции, упрощающие использование шаблона кода.

Где находится файл wp-config.php в WordPress

Чтобы найти файл wp-config.php в корневом каталоге вашего сайта WordPress, используйте файловый менеджер, предоставленный вашим веб-хостингом, или FTP-клиент. В следующем разделе показано, как найти файл wp-config.php в популярной панели cPanel и по FTP.

Поиск файла wp-config.php через cPanel

cPanel предоставляет встроенный файловый менеджер. Выполните следующие действия, чтобы найти файл wp-config.php в cPanel:

  1. Перейдите к диспетчеру файлов в разделе «Файлы» вашей cPanel.

cPanel файл менеджер

  1. Перейдите в каталог (папку) public_html -> wp (wp в данном случае название вашего сайта) в боковой панели.
  2. Прокрутите вниз, пока не найдете файл wp-config.php.

настройка файла wp-config.php

Поиск файла wp-config.php через FTP

Вы также можете использовать FTP-клиент, чтобы найти файл wp-config.php. Можете воспользоваться программой FileZilla.

Инструкция как найти файл wp-config.php через FTP-клиент:

  1. Получите данные для соединения через FTP у вашего хостинг-провайдера. Это логин, пароль, сервер и порт.
  2. Откройте FileZilla и введите свои данные для соединения через FTP. Нажмите Quickconnect.

Соединение через FTP

  1. Перейдите в корневой каталог вашего (обычно это ваш домен в public_html). Там должен быть файл wp-config.

найти wp-config.php файл. настройка файла wp-config.php

Перемещение файла wp-config.php

Поскольку файл конфигурации вашего веб-сайта WordPress хранится в корневой папке, файл становится уязвимым для атак злоумышленников.

В дополнение к настройке прав доступа к файлу мы рекомендуем переместить файл из его местоположения по умолчанию, чтобы усилить безопасность вашего веб-сайта WordPress.

Выполните следующие действия, чтобы переместить файл WordPress wp-config.php с помощью файлового менеджера:

  1. Найдите файл wp-config.php в корневом каталоге вашего веб-сайта WordPress.
  2. Скопируйте весь код и вставьте в новый файл php в другой каталог по вашему выбору. Например переместите его внутрь /public_html/wp-admin/user.
  3. Измените имя нового файла wp-config. Цель состоит в том, чтобы замаскировать его под неважный файл, чтобы хакеры его не узнали. Например задайте search-console.php в качестве названия.
  4. Вернитесь к исходному файлу wp-config который лежит в корне и замените все его содержимое следующим кодом:
<?php
include('/domains/yourdomain.com/public_html/wp-admin/user/search-console.php');
?>
  1. Обязательно исправьте путь с новым местоположением файла, search-console.php и измените свой домен.

Вот и все. Исходный файл wp-config теперь будет служить ярлыком, который перенаправляет ваш сервер на фактический другой спрятанный файл wp-config.

Разделы файла wp-config.php

Как упоминалось ранее, файл WordPress wp-config-sample.php можно использовать, чтобы создать конфигурацию для вашего веб-сайта WordPress. Поэтому важно знать назначение каждого раздела и способы его изменения.

В этом разделе будет представлена разбивка разделов в файле wp-config и фрагменты кода, которые необходимо добавить для расширенной настройки веб-сайта WordPress.

Настройки MySQL в wp-config.php

Раздел настроек MySQL состоит из конфигурации вашей базы данных WordPress — имени хоста MySQL, имени базы данных, имени пользователя и пароля. Мы рекомендуем изменить этот раздел, если ваш хостинг-провайдер использует другой номер порта или вы переходите на другой веб-сервер.

Вот фрагмент настроек MySQL, взятый из файла wp-config-sample.php:

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'database_name_here' );
/** MySQL database username */
define( 'DB_USER', 'username_here' );
/** MySQL database password */
define( 'DB_PASSWORD', 'password_here' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

Вся информация, необходимая для этого раздела (имя базы, логин, пароль и хост), доступна в панели управления хостингом.

Настройка кодировки для Базы Данных

WordPress настраивает кодировку базы данных и значения сортировки базы данных в файле wp-config.php. Его цель — определить таблицы базы данных с соответствующими настройками кодировки, такими как:

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

По умолчанию WordPress устанавливает кодировку UTF8, поскольку он поддерживает все языки, что делает его идеальным для современных данных. Между тем, значение сопоставления базы данных в основном зависит от кодировки, поскольку она определяет, как база данных WordPress сортирует и сравнивает ваши данные.

MySQL автоматически присваивает значение сопоставления базы данных на основе кодировки, следовательно, пустое значение по умолчанию. Если ваша база данных WordPress использует кодировку UTF8, то значение сортировки по умолчанию — utf8_general_ci.

Однако можно вручную назначить значение сопоставления, если кодировка не совпадает с отображаемым, например, для японского языка. Мы рекомендуем не изменять этот раздел, если вы не разбираетесь в SQL, MySQL и MariaDB. Использование неправильной комбинации кодировки и значений сортировки приведет к различным ошибкам базы данных в WordPress.

Ключи безопасности

В файле wp-config хранится набор ключей аутентификации и salt WordPress, обеспечивающих дополнительный уровень безопасности вашего веб-сайта от атак Brute Force. Эти случайные строки данных содержат восемь переменных, каждая из которых шифрует информацию для входа, сохраняемую файлами cookie при входе на веб-сайт.

Учитывая их назначение, периодическая смена ключей аутентификации и salt— один из многих способов повысить безопасность WordPress. Мы рекомендуем использовать генератор паролей или протестировать созданные вами пароли с помощью средства проверки паролей, чтобы обеспечить его устойчивость к атакам с подбором пароля.

Кроме того, установите плагин безопасности WordPress, такой как Salt Shaker, чтобы автоматически генерировать для вас salt ключи. Получив пароли, вставьте их один за другим внутри к.

/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
*
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define( 'AUTH_KEY',         'put your unique phrase here' );
define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
define( 'NONCE_KEY',        'put your unique phrase here' );
define( 'AUTH_SALT',        'put your unique phrase here' );
define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
define( 'NONCE_SALT',       'put your unique phrase here' );
/**#@-*/

После изменения новых ключей безопасности и salt ключей, WordPress выкинет всех пользователей из их профиля и сделает текущие файлы cookie недействительными. Пользователям нужно будет сделать повторный вход в систему, чтобы получить доступ к вашему сайту.

Префикс таблицы базы данных

WordPress устанавливает префикс базы данных wp_ в файле wp-config. Как и в случае с ключами безопасности, мы рекомендуем изменить префикс базы данных при первой же возможности. Это повысит безопасность вашей базы данных от атак путем SQL инъекций.

Следующий фрагмент кода — это раздел в файле wp-config, в котором хранится префикс вашей базы данных:

/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix  = 'wp_';

Как упоминалось выше, WordPress позволяет изменять префикс базы данных, состоящий из символов подчеркивания, букв и цифр. Убедитесь, что он достаточно уникален, чтобы другие пользователи не могли его легко угадать. Например:

$table_prefix  = 'wp_customprefix_';

Убедитесь, что вы успешно изменили префикс таблиц в базе данных, проверив ее через phpMyAdmin. Если вы обращаетесь к своей структуре базы данных, имена таблиц должны начинаться с назначенного вам префикса. Здесь мы заменяем префикс таблицы по умолчанию на wp_customprefix_.

база данных mySQL. настройка файла wp-config.php

Режим отладки

Если вы разработчик WordPress, вам будет полезен этот параметр wp-config. Режим отладки отвечает за уведомление всякий раз, когда сайт WordPress выполняет код PHP, что позволяет вам проверить, есть ли ошибка в вашем коде.

Следующий фрагмент кода — это раздел в файле WordPress wp-config, в котором хранятся ваши настройки режима отладки:

/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the documentation.
*
* @link https://wordpress.org/support/article/debugging-in-wordpress/
*/
define( 'WP_DEBUG', false );

WordPress отключает режим отладки по умолчанию. Чтобы включить этот режим, замените значение false на true.

define( 'WP_DEBUG', true );

Имейте в виду, что включение режима отладки заставит ваш веб-сайт WordPress отображать все ошибки и предупреждения PHP, а не только показывать белый экран смерти для фатальных ошибок.

Абсолютный путь

Данный раздел указывает расположение папки или файла на компьютере. Он определяет отношения между папками и файлами, а также основу URL-адреса вашего сайта.

Тем не менее, вы не должны изменять информацию в следующем фрагменте кода:

/* That's all, stop editing! Happy publishing. */
/** 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';

URL-адрес WordPress

Изменение URL-адреса WordPress является необходимым шагом, если вы хотите переместить сайт на другой сервер или домен. Это можно сделать через меню «Настройки» -> «Основные» в панели управления WordPress.

админ панель wordpress

Иногда вы не можете редактировать эти значения адреса WordPress и адреса сайта из-за ошибки ERR_TOO_MANY_REDIRECTS. В этом случае вы можете изменить свой URL-адрес WordPress, добавив следующий фрагмент кода в файл wp-config.php.

define( 'WP_HOME', 'http://example.com' );
define( 'WP_SITEURL', 'http://example.com' );

Обязательно замените значение http://example.com своим доменным именем и поместите код над строкой /* That’s all, stop editing! Happy publishing.*/. Включите www-версию вашего веб-сайта, если вы используете URL-адрес www.

Ограничение лимита памяти. Настройка файла wp-config.

WordPress требует памяти PHP для выполнения скриптов. Объем памяти, которую вы получаете, зависит от вашего веб-хостинга. Например, это может быть 512 МБ максимального лимита памяти для планов общего веб-хостинга.

Если для использования WordPress недостаточно памяти, он отобразит сообщение об ошибке исчерпания памяти. Чтобы решить эту проблему, установите собственное ограничение памяти PHP, добавив следующий фрагмент кода в файл wp-config перед строкой /* That’s all, stop editing! Happy publishing. */.

В этом примере мы увеличим объем выделяемой памяти до 256 МБ для каждого PHP-скрипта.

define('WP_MEMORY_LIMIT', '256M');

Мы рекомендуем установить значение ограничения памяти PHP в соответствии с вашими потребностями, одновременно применяя максимальное ограничение памяти для каждого скрипта. WordPress будет применять этот лимит памяти только в том случае, если скрипту требуется больше памяти, чем выделено.

Не переусердствуйте с предельным значением памяти, так как избыток памяти PHP увеличивает вероятность того, что мошеннические скрипты PHP будут потреблять оперативную память сервера.

define('WP_MAX_MEMORY_LIMIT', '512M');

Каталог для загрузок

WordPress перенаправляет все загруженные вами медиафайлы в каталог /wp-content/uploads/. Чтобы повысить безопасность ваших файлов, вы можете переопределить путь загрузки на своем сайте WordPress.

Добавьте следующий фрагмент кода под кодом с определением константы WP_DEBUG вашего файла wp-config.php:

define( 'UPLOADS', 'wp-content/media' );

Этот код заставит WordPress хранить все загруженные мультимедиа в новом каталоге media в папке wp-content. Не стесняйтесь изменять имя нового каталога по желанию.

Если вы хотите, чтобы WordPress хранил ваши медиафайлы в каталоге вне wp-content, используйте следующий фрагмент кода, чтобы определить путь загрузки.

define( 'UPLOADS', ''.'media' );

Имейте в виду, что оба фрагмента кода работают только для определения новой папки для загрузок внутри корневого каталога или абсолютного пути (ABSPATH). В случае если вы изменили путь загружаемых файлов обязательно измените URL-адрес каждого файла в таблицах базы данных WordPress, чтобы избежать неработающих ссылок на вашем сайте.

Каталог wp-content

Помимо медиафайлов, WordPress также хранит файлы плагинов и тем в папке wp-content. Поскольку этот путь к папке является настройкой WordPress по умолчанию, он очень подвержен атакам с внедрением вредоносных скриптов. Поэтому лучше всего изменить расположение папки wp-content.

Отредактируйте файл wp-config.php, добавив собственный код после следующей строки:

/* Add any custom values between this line and the "stop editing" line. */

Вам нужно определить константу WP_CONTENT_DIR и изменить расположение вашей папки wp-content:

define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/content/wp-content' );

Чтобы изменить расположение URL-адреса wp-content, необходимо определить еще одну переменную:

define( 'WP_CONTENT_URL', 'yourdomain.com/blog/content/wp-content' );

Не забудьте заменить yourdomain.com своим собственным доменом.

Каталог для плагинов

Если перемещение папки wp-content кажется хлопотным, рассмотрите вместо этого перемещение папки плагинов. Для этого вам нужно определить постоянную переменную WordPress wp_plugin_dir, добавив следующий фрагмент кода под разделом wp-settings:

define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/content/wp-content/plugins' );

Обязательно измените URL-адрес папки плагина в переменной wp_plugin_url, добавив следующий код:

define( 'WP_PLUGIN_URL', 'yourdomain.com/blog/content/wp-content/plugins');

Некоторые разработчики плагинов используют переменную plugindir для запуска своих программ. Не забудьте также изменить его, чтобы избежать конфликтов плагинов на вашем сайте WordPress.

define( 'PLUGINDIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/content/wp-content/plugins' );

Каталог для тем

Мы не рекомендуем перемещать папку с темами, так как это может вызвать конфликты плагинов. Если вам нужен дополнительный каталог тем, создайте его с помощью функции register_theme_directory:

function register_theme_directory( $directory ) {
    global $wp_theme_directories;
 
    if ( ! file_exists( $directory ) ) {
        // Try prepending as the theme directory could be relative to the content directory.
        $directory = WP_CONTENT_DIR . '/' . $directory;
        // If this directory does not exist, return and do not register.
        if ( ! file_exists( $directory ) ) {
            return false;
        }
    }
 
    if ( ! is_array( $wp_theme_directories ) ) {
        $wp_theme_directories = array();
    }
 
    $untrailed = untrailingslashit( $directory );
    if ( ! empty( $untrailed ) && ! in_array( $untrailed, $wp_theme_directories, true ) ) {
        $wp_theme_directories[] = $untrailed;
    }
 
    return true;
}

Имейте в виду, что новый каталог темы должен находиться в корневом каталоге. Это связано с тем, что ваш сервер должен иметь доступ к файлам темы веб-сайта, чтобы они работали.

Логирование ошибок

Включение режима отладки в WordPress помечает только ошибки на бэкенде и интерфейсе вашего сайта. Чтобы логировать ошибки (записать в кудато), вам нужно добавить сопутствующий код ниже строки define(‘WP_DEBUG’, true);

define( 'WP_DEBUG_LOG', true );

Если вы хотите сохранить ошибки в файле, используйте этот код:

define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );

Чтобы отключить вывод ошибок, что означает, что ваш браузер не будет отображать какую-либо информацию во время процесса отладки, используйте этот код:

define( 'WP_DEBUG_DISPLAY', false );

Автоматические обновления WordPress

WordPress предоставляет возможность включить функцию автоматического обновления в процессе установки, что избавит вас от необходимости делать это вручную. Однако это может иметь неприятные последствия, если вы установите пользовательскую тему, поскольку неизвестно, какое обновление может повлиять на внешний вид вашего сайта.

Чтобы отключить функцию автоматического обновления, над строкой /* That’s all, stop editing! Happy publishing. */ добавьте следующий код:

define( ‘AUTOMATIC_UPDATER_DISABLED’, true );

Замените значение true на false или удалите этот код, если вы хотите снова включить авто-обновления в будущем.

Обновления ядра WordPress (настройка файла wp-config.php)

Начиная с WordPress версии 3.7 и выше поставляется с автоматическими обновлениями в фоновом режиме для второстепенных выпусков ядра и файлов перевода для обеспечения оптимальной производительности. В некоторых случаях обновления могут включать в себя файлы разработки тем и плагинов.

Поскольку эта функция обеспечивает актуальность и безопасность вашего сайта, мы рекомендуем оставить ее по умолчанию.

Чтобы разрешить, незначительные и основные обновления ядра, добавьте следующий код над строкой /* That’s all, stop editing! Happy publishing. */:

define( 'WP_AUTO_UPDATE_CORE', true );

Измените постоянное значение на false, чтобы отключить разработку, второстепенные и основные обновления ядра:

define( 'WP_AUTO_UPDATE_CORE', false);

В качестве альтернативы включите авто-обновления только для второстепенных выпусков, изменив постоянное значение на второстепенное:

define( 'WP_AUTO_UPDATE_CORE', 'minor');

Собственная таблица пользователей

По умолчанию WordPress предоставляет вам таблицу wp_users для хранения пользовательских данных. Если вам нужна собственная таблица пользователей после установки, добавьте следующий код в файл wp-config.php:

define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' );

Обычно разработчики используют этот код для совместного использования таблиц пользователей между установками WordPress, что полезно для поддержания одной и той же базы пользователей на нескольких веб-сайтах.

Собственная таблица для метаданных пользователей

Если вы решите создать собственную таблицу пользователей, вам придется создать еще одну для хранения метаданных пользователей.

define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' );

Пользовательская мета-таблица пользователей полезна для сбора и обмена информацией о пользователях в нескольких установках WordPress. Плагины членства также используют пользовательские мета-таблицы для хранения информации о членстве.

Настройки языка и каталог для хранения файлов перевода

Язык по умолчанию для установки WordPress — английский. WordPress версии 4.0 и выше позволяет пользователям изменить его в меню «Настройки» -> «Основные» в панели администратора. Также можно изменить язык по умолчанию в процессе установки.

изменить язык в WordPress. настройка файла wp-config.php

Если вы хотите переключиться на другой язык, добавьте следующий код в файл wp-config:

define( ‘WPLANG’, ‘de_DE’ );
define( ‘WP_LANG_DIR’, dirname(__FILE__) . ‘wordpress/languages’ );

Первая строка кода указывает, какой языковой файл .mo необходимо установить, а вторая определяет языковой каталог, в котором хранится языковой файл.

Соглашение об именах языковых файлов основано на коде языка, за которым следует код страны. Например, de_DE относится к немецкому языку. Найдите нужный язык и код страны на странице утилит GNU gettext.

Если вы введете неправильную комбинацию кода страны и языка, WordPress по умолчанию будет использовать английский язык (США).

Права доступа к файлам. Настройка файла wp-config.php

Настройка прав доступа к файлам — еще один важный шаг для защиты вашего сайта. Параметр определяет, какие пользователи могут просматривать, изменять и выполнять основные файлы и папки на вашем сайте. Большинство хостинг-провайдеров позволяют изменять права доступа к файлам и папкам через файловый менеджер.

Каждый уровень разрешений для соответствующего пользователя представлен трехзначным кодом, состоящим из:

  • 0 ‒ нет доступа
  • 1 ‒ выполнить
  • 2 ‒ написать
  • 4 ‒ читать
  • 3 (комбинация 2 и 1) ‒ записать и выполнить
  • 5 (комбинация 4 и 1) ‒ прочитать и выполнить
  • 6 (комбинация 4 и 2) ‒ чтение и запись
  • 7 (комбинация 2 и 3) ‒ чтение, запись и выполнение

Если вы не можете получить доступ к диспетчеру файлов, чтобы изменить права доступа к файлам, измените файл wp-config, используя комбинацию приведенного выше кода. Добавьте следующий код над строкой /* That’s all, stop editing! Happy publishing. */:

define( 'FS_CHMOD_DIR', ( 0755 & ~ umask() ) );
define( 'FS_CHMOD_FILE', ( 0644 & ~ umask() ) );
chmod 644 wp-config.php
chmod 644 .htaccess

Разрешения 644 файлов для wp-config, .htaccess и других файлов делают их видимыми для всех пользователей, но изменить их может только их владелец. Между тем, 755 прав доступа к файлам для каталогов и подкаталогов WordPress означают, что каждый может читать и выполнять их, но только владелец может вносить изменения.

Предупреждение! Никогда не устанавливайте права доступа к файлам на 777, так как это даст всем доступ для чтения, записи и выполнения ваших файлов. С другой стороны, права доступа 000 и 444 сломают ваш сайт, поскольку они не позволят WordPress редактировать и выполнять файлы тем и плагинов.

Заключение по настройке файла wp-config.php

wp-config.php — это основной файл WordPress, созданный в процессе установки веб-сайта. Он устанавливает соединение между вашим веб-сайтом WordPress и его базой данных, а также реализует расширенные настройки для обоих. Вы можете найти его в корневой папке вашего веб-сайта с помощью FTP-клиента или файлового менеджера вашего хостинг-провайдера.

Конфигурационный файл WordPress состоит из нескольких разделов:

  • Настройки MySQL — конфигурация базы данных WordPress.
  • Кодировка базы данных — используются для определения таблиц с соответствующими настройками кодировки.
  • Ключи безопасности ‒ отвечают за шифрование информации пользователя.
  • Префикс таблицы базы данных WordPress — установите префикс таблицы для большей безопасности.
  • Режим отладки — помогает отслеживать ошибки PHP.
  • Абсолютный путь — указывает расположение папки или файла на компьютере.

Хотя WordPress wp-config.php можно редактировать с помощью текстового редактора, обязательно сделайте резервную копию файла, прежде чем вносить какие-либо изменения. Даже самая незначительная неправильная конфигурация может нарушить связь между базой данных и вашим сайтом WordPress.

Admin bar avatar

Александр Сокирка

Занимаюсь веб разработкой с 2007 года. Имею большой опыт в веб-дизайне и разработке сайтов. Являюсь автором YouTube канала Быть Программистом. Основатель бренда Aletheme и автор тем для WordPress на маркетплэйсе Envato. С 2017 года занимаюсь обучением людей желающим стать программистами. Мои обучающие программы можно найти на этом сайте или на Udemy.

Добавить комментарий