Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

zh-cn:编辑 wp-config.php

本文已被标记为未完成状态。您可以将其补充或翻译完整,以此帮助完善 Codex。
WARNING: 在您编辑这个页面之前

请不要把您自己服务器的配置信息复制到这个 Codex 页面上,因为那会使所有人都能轻易访问您的服务器。谢谢!

作为 WordPress 安装过程的一部分,您需要修改 wp-config.php 文件,配置 WordPress 访问 MySQL 数据库所必需的信息等内容。

wp-config.php 一开始是不存在于 WordPress 中的,您需要自己创建。请参照 wp-config-sample.php 文件样本来进行创建。高级设定及示例会在后文中说明。

要对 wp-config.php 文件做修改,您需要如下信息:

数据库名称 
WordPress 所使用的数据库名称
数据库用户名 
访问数据库所需的用户名
数据库密码 
用户名对应的用以访问数据库的密码
数据库主机 
数据库服务器的主机名称

如果您的主机供应商已为您安装好了 WordPress 的话,可以向他们索要相关信息。如果你是自己配置的服务器或主机帐号的话,就需要创建数据库及用户来获取以上这些信息了。

本文已被标记为需要加工。欢迎您踊跃编辑,来帮助 Codex。

配置数据库设定

重要:千万不要使用如Microsoft Word类型的文字处理程序来编辑WordPress文件!

在WordPress目录的基础目录下找到wp-config-sample.php文件,并使用文本编辑器(text editor)打开。

NOTE: 从2.6版开始,wp-config.php可被直接移至WordPress应用程序目录的上级目录中。

默认的wp-config-sample.php

这是默认的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' ); 
NOTE: Text inside /* */ are comments, for information purposes only.
NOTE: 编辑这个页面时,请不要使用您自己服务器的配置。


设定数据库名称

putyourdbnamehere替换为你的数据库名称,比如:MyDatabaseName

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

设定数据库用户名

usernamehere替换为你的用户名,比如:MyUserName

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

设定数据库密码

yourpasswordhere替换为你的密码,比如:MyPassWord

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

设定数据库主机

localhost替换为你的数据库主机,比如:MyDatabaseHost

define( 'DB_HOST', 'MyDatabaseHost' ); // Example MySQL Database host
NOTE: 基本上说来你是无需修改此项的。如果你确定的话,可以使用默认值'localhost'进行安装,然后看看是否可行。如果没有成功,请联系你的网络主机供应商。

可能的DB_HOST值

不同的主机供应商会对mysql使用不同的网络设定。如果在下表左侧能找到你的主机供应商的话,那么右侧就是DB_HOST较准确的值了。你可以联系相关技术支持和/或查找你所使用的主机供应商的在线资料进行进一步确认。

Hosting Company DB_HOST Value Guess
1and1 db12345678
AN Hosting localhost
A Small Orange localhost
BlueHost localhost
DreamHost mysql.example.com
GoDaddy h41mysql52.secureserver.net
HostGator localhost
HostICan localhost
ICDSoft localhost:/tmp/mysql5.sock
LaughingSquid localhost
MediaTemple GridServer internal-db.s44441.gridserver.com
one.com localhost
pair Networks dbnnnx.pair.com
Yahoo mysql
Hosts with cPanel localhost
Hosts with Plesk localhost
Hosts with DirectAdmin localhost
Tophost.it sql.your-domain-name.it



MySQL备用端口

如果你的主机为数据库使用备用端口的话,就需要修改wp-config.php中的DB_HOST值以反映出主机备用端口设置。

对localhost

 define('DB_HOST', 'localhost:3307');

其他

define('DB_HOST', 'mysql.example.com:4454');

数据库字符集

WordPress 2.2版中,DB_CHARSET可用,以允许数据库字符集的标识(如TIS620 Thai,tis620)在定义MySQL数据库表时被使用。

在你尚未完全理解修改utf8(Unicode UTF-8) 默认值所带来的后果之前,不应做任何修改。请注意UTF-8支持着诸多欧洲语言,因此将DB_COLLATEutf8的设置放着别动,而应为你的语言使用合适的DB_COLLATE值。

此例表明WordPress默认值的utf8:

define('DB_CHARSET', 'utf8');
WARNING: 对于执行新安装的用户

一般说来不应修改DB_CHARSET的默认值。如果你的博客需要使用不同的字符集,请阅读字符集和排序MySQL支持以明确有效的DB_CHARSET值。

WARNING: 对于执行升级的用户(尤其是对那些2.2之前的博客系统)

如果wp-config.php文件中不存在DB_CHARSET和DB_COLLATE的话,请勿wp-config.php添加定义,除非你已阅读并理解数据库字符集转换。对于已存在的博客,向wp-config.php文件添加DB_CHARSET和DB_COLLATE会出不少问题。

数据库排序

WordPress2.2版中,DB_COLLATE可用,以允许数据库排序(即字符集的排序次序)。大多数情况下,此值应留空(null),这样数据库排序才能被MySQL字段分配,这是基于DB_CHARSET所指定的数据库字符集之上的。将DB_COLLATE设为UTF-8字符集中定义的某个UTF-8值。

WordPress的默认DB_COLLATE值:

define('DB_COLLATE', ); 

UTF-8 Unicode一般排序

define('DB_COLLATE', 'utf8_general_ci');

UTF-8 Unicode 土耳其语排序

define('DB_COLLATE', 'utf8_turkish_ci');
WARNING: 对于执行新安装的用户

一般不应修改DB_COLLATE的默认值。将其留空(null)能保证在数据库表格被创建时,排序能自动为MySQL所分派。

WARNING: 对于执行升级的用户(尤其是对那些2.2之前的博客系统)

如果wp-config.php文件中不存在DB_CHARSET和DB_COLLATE的话,请勿向wp-config.php添加定义,除非你已阅读并理解数据库字符集转换。而你还可能需要升级WordPress。

安全密钥

2.6版开始,存在3种安全密钥,AUTH_KEYSECURE_AUTH_KEYLOGGED_IN_KEY,它们能够保证用户cookies中的信息得到更好的加密。在2.7版中引入了第四种密钥,NONCE_KEY

你无需记住这些密钥,只要保证它们越长越复杂越好,你可以使用在线密钥生成器

示例:

define('AUTH_KEY', ':dr+%/5V4sAUG-gg%aS*v;&xGhd%{YKC^Z7KKGh j>k[.Nf$y7iGKdJ3c*[Kr5Bg');
define('SECURE_AUTH_KEY', 'TufWOuA _.t>#+hA?^|3RfGTm>@*+S=8\"\'+\"}]<m#+}V)p:Qi?jXLq,<h\\`39m_(');
define('LOGGED_IN_KEY', 'S~AACm4h1;T^\"qW3_8Zv!Ji=y|)~5i63JI |Al[(<YS<2V^$T])=8Xh2a:b:}U_E');
define('NONCE_KEY', 'k1+EOc-&w?hG8j84>6L9v\"6C89NH?ui{*3\\(t09mumL/fFP_!K$JCEkLuy ={x{0');

密钥是一种加入到密码中的干扰信息,用于提高您站点以及帐号的安全性。

简单来说,密钥就是一种用于增加密码强度、抗暴力破解的安全机制。例如 "password" 或 "test" 这类的密码很容易会被猜解出来。但像 "88a7da62429ba6ad3cb3c76a09641fc" 这种没有规律的密码,则需要很多年的时间才能猜测出来。

更多关于密钥和密码安全的技术细节,可参见以下资源列表:

高级选项

以下的部分可能包含高级的或者不成熟的信息,在正式使用前,请先确保你已经执行常规备份并且了解如何恢复系统。


数据库表格前缀

$table_prefix是被放在你的数据库表格前面部分的设定值, 数据库前缀的设置对提高你的站点安全以及在同一数据库中安装多个WordPress站点都非常有用,通过改变默认值“wp_” 为随机独一的值,可减轻站点受攻击的可能性,总体上提高你的网站安全性。

// 你可以将多个博客安装到同一个数据库,如果你为它们设置不同的前缀。
$table_prefix  = 'r235_';   // Only numbers, letters, and underscores please!

在同一个数据库上安装第二个博客的时候,可以通过指定不同的前缀来安装。

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

WordPress地址(URL)

WP_SITEURL, defined since WordPress Version 2.2, allows the WordPress address (URL) to be defined. The valued 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 and disables the WordPress address (URL) field in the Administration > Settings > General panel.

NOTE: It won't change the Database value though, and the url will revert to the old database value if this line is 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/wordpressp');
NOTE: A safer alternative for some installations would be to use the server-generated SERVER_NAME instead of the php/user-generated HTTP_HOST which 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 is set by the server configuration and is static.

Dynamically set WP_SITEURL based on $_SERVER['SERVER_NAME']

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

博客地址(URL)

WP_HOME is another wp-config.php option added in WordPress Version 2.2. Similar to WP_SITEURL, WP_HOME overrides the wp_options table value for home but does not change it permanently. 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.

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');

迁移目录wp-content

Since Version 2.6, 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', $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-content' );

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

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

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

define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/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', $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-content/plugins' );

Modify AutoSave Interval

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将会自动为您保存编辑中的文章和页面,允许您恢复文章和页面的各个版本。此功能可以通过修改参数禁用,您也可以指定自动保存草稿数量的最大参数。


关闭文章修订

如果您 没有设置 这个参数, WordPress默认WP_POST_REVISIONStrue (默认开启文章修订功能). 如果您想关闭自动保存功能,请参考使用以下代码:

define('WP_POST_REVISIONS', false );

指定修订数量

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

define('WP_POST_REVISIONS', 3);

Set Cookie Domain

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

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


Debug

The WP_DEBUG option, added in WordPress Version 2.3.1, controls the display of some errors and warnings. If this setting is absent from wp-config.php, then the value is assumed to be false.

NOTE: The true and false values in the example are not set in apostrophes (') because they are boolean values.
define('WP_DEBUG', true);
define('WP_DEBUG', false);

Additionally, if you are planning on modifying some of WordPress' built-in JavaScript, you should enable the following option:

define('SCRIPT_DEBUG', true);

This will allow you to edit the scriptname.dev.js files in the wp-includes/js and wp-admin/js directories.

In Wordpress versions since 2.3.2, database errors are printed only if WP_DEBUG is set to true. In earlier versions, database errors were always printed. (Database errors are handled by the wpdb class and are not affected by PHP's error settings.)

In WordPress version 2.5, 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.

Disable Javascript Concatenation

To result in a faster administration area, all Javascript files are concatenated into one URL. If Javascript is failing to work in your administration area, you can try disabling this feature:

define('CONCATENATE_SCRIPTS', false);

Configure Error Log

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.

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. */


Increasing memory allocated to PHP

Also released with Version 2.5, the 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 32MB (code is at beginning of wp-settings.php), so the setting in wp-config.php should reflect something higher than 32MB.

Please note, this setting may not work if your host does not allow for increasing the PHP memory limit--in that event, contact your host to increase the PHP memory limit. Also, note that many hosts set the PHP limit at 8MB.

Increase PHP Memory to 64MB

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

Increase PHP Memory to 96MB

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


Cache

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 and Usermeta Tables

CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE are used to designated 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');


Language and Language Directory

WPLANG defines the name of the language translation (.mo) file. LANGDIR defines what directory the WPLANG .mo file resides. If LANGDIR 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('LANGDIR', 'mylanguagedirectory');


Save queries for analysis

The SAVEQUERIES definition saves the database queries to a 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, put this in wp-config.php:

define('SAVEQUERIES', true);

Then in the footer of your theme put this:

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

Override of default file permissions

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 (e.g. some Italian 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. Note that the '0755' is an octal value and is not delineated with single quotes ('). See Also: Changing File Permissions

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

FTP/SSH Constants

To enable SSH2 as an upgrade option you will need to install the pecl SSH2 extension. To install this library 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

These methods for the WordPress core, plugin, and theme upgrades try to determine the WordPress path, as reported by PHP, but symlink trickery can sometimes 'muck this up' so if you know the paths to the various folders on the server, as seen via your FTP user, you can manually define them in the wp-config.php file.

The following are valid constants for FTP/SSH updates:

  • FS_METHOD forces the filesystem method. It should only be "direct", "ssh", "ftpext", or "ftpsockets".
  • FTP_BASE is the full path to the "base" 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 standard FTP port is 21 and the standard SSH port is 22.
  • FTP_SSL TRUE for SLL-connection.
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:21');
define('FTP_SSL', false);

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.

If you're still not clear on how to use SSH for upgrading or installing WordPress/plugins, read through this tutorial.

Alternative Cron

Use this, for example, if scheduled posts are not getting published. According to Otto's forum explanation, "this alternate method uses a redirection approach, which makes 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 is a bit iffy sometimes, which is why it's not the default."

define('ALTERNATE_WP_CRON', true);


额外的定义常量

Here are additional constants that can be defined, but probably shouldn't be. The Cookie definitions are 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('DISABLE_WP_CRON', true);

清空垃圾箱时间设置

Added with Version 2.9, 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. Note that WordPress will not ask for confirmation when someone clicks on "Delete Permanently".

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

自动优化数据库

Added with Version 2.9, there is automatic database optimization support, which you can enable by adding the following define to your wp-config.php file only when the feature is required

 define('WP_ALLOW_REPAIR', true);

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

Please Note: That this define enables the functionality, The user does not need to be logged in to access this functionality when this define is set. This is because its main intent is to repair a corrupted database, Users can often not login when the database is corrupt.

查看所有定义的常量

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

 print_r(@get_defined_constants());

禁用 WordPress 自动更新

把以下代码添加到 /* 好了!请不要再继续编辑。请保存本文件。使用愉快! */ 上面

 # 禁用所有自动更新:
 define( 'AUTOMATIC_UPDATER_DISABLED', true );

禁用 WordPress 核心更新

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

在保存之前检查

请务必仔细检查以上你所设置的、引导、/(斜杠)、或尾随空格,不要删除单引号!

在你保存文件前,一定要“double-check '你不小心删除任何单引号的参数值。确保没有文件中关闭的PHP标签后。文件中的最后一项应该是”?>”或者别的什么。没有空间。

保存文件,选择文件>保存> wp-config。php”和保存文件的根在你的WordPress安装。将文件上传到您的Web服务器和你准备安装WordPress!

参考