¿Las mejores prácticas para las versiones wp-config.php?

34

¿Existe alguna práctica recomendada para incluir su archivo wp-config.php en su repositorio de control de versiones?

Estoy considerando crear un nuevo sitio con este tipo de configuración, (similar a Alex King y Mark Jaquith ):

/index.php
/local-config.php
/wp-config.php
/wp/ (core)
/wp-content/ (plugins, themes, etc.)

¿Cómo puedo hacer esto sin exponer mis contraseñas a git, en caso de que este repositorio se vuelva público?

Especialmente en la publicación de Mark, parece que local-config.php puede almacenar detalles de la base de datos local y contraseñas, pero las de producción permanecen en wp-config.php. ¿Esto es demasiado problema? ¿Debo dejar wp-config.php sin versión?

    
pregunta jjeaton 20.05.2012 - 07:44

4 respuestas

43

Aquí es cómo lo hago y no he encontrado nada mejor que esto. Mantengo una versión diferente del archivo wp-config.php bajo el control de versiones y luego mantengo un archivo en el directorio superior que contiene todas las credenciales de la base de datos y las sales / keys. También de esta manera, puedo distinguir entre el tipo de configuración que estoy ejecutando y hacer las cosas de forma diferente en función de eso.

Aquí está el wp-config.php que mantengo bajo git ( enlace ):

<?php

/**
* Define type of server
*
* Depending on the type other stuff can be configured
* Note: Define them all, don't skip one if other is already defined
*/

define( 'DB_CREDENTIALS_PATH', dirname( ABSPATH ) ); // cache it for multiple use
define( 'WP_LOCAL_SERVER', file_exists( DB_CREDENTIALS_PATH . '/local-config.php' ) );
define( 'WP_DEV_SERVER', file_exists( DB_CREDENTIALS_PATH . '/dev-config.php' ) );
define( 'WP_STAGING_SERVER', file_exists( DB_CREDENTIALS_PATH . '/staging-config.php' ) );

/**
* Load DB credentials
*/

if ( WP_LOCAL_SERVER )
    require DB_CREDENTIALS_PATH . '/local-config.php';
elseif ( WP_DEV_SERVER )
    require DB_CREDENTIALS_PATH . '/dev-config.php';
elseif ( WP_STAGING_SERVER )
    require DB_CREDENTIALS_PATH . '/staging-config.php';
else
    require DB_CREDENTIALS_PATH . '/production-config.php';

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

if ( ! defined( 'AUTH_KEY' ) )
    define('AUTH_KEY', '9*W=5&lt;Rw-)c].9}g?^[:!j]h+Efr&lt;y$&lt;YmV0XOo|lOIujEE}+[R}iAQZ :Sy3wN}');
if ( ! defined( 'SECURE_AUTH_KEY' ) )
    define('SECURE_AUTH_KEY', 'APge3~H;g+b0FyNF&amp;e'[email protected]^Q4(@p#kDa=NR? $Z9|@v*a(tOj*B+.');
if ( ! defined( 'LOGGED_IN_KEY' ) )
    define('LOGGED_IN_KEY', '5l0+:WTpj8#[V|;&lt;Iw;%rkB(A}r++HwT|s[LW!.wt.=5J!b%Z{F1/[LxQ*d7J&gt;Cm');
if ( ! defined( 'NONCE_KEY' ) )
    define('NONCE_KEY', 'zO2cmQX'Kc~_XltJR&amp;T !Uc72=5Cc6'SxQ3;$f]#J)p&lt;/wwX&amp;7RTB2)K1Qn2Y*c0');
if ( ! defined( 'AUTH_SALT' ) )
    define('AUTH_SALT', 'je]#Yh=RN DCrP9/N=IX^,[email protected],|@L]at .-,yc^-^+?0ZfcHjD,WV');
if ( ! defined( 'SECURE_AUTH_SALT' ) )
    define('SECURE_AUTH_SALT', '^'6z+F!|+$BmIp&gt;y}Kr7]0]Xb@&gt;2sGc&gt;Mk6,$5FycK;u.KU[Tw$345K9qoF}WV,-');
if ( ! defined( 'LOGGED_IN_SALT' ) )
    define('LOGGED_IN_SALT', 'a|+yZsR-k&lt;[email protected]~v82a_+{+hRCnL&amp;|aF|Z~yU&amp;V0IZ}[email protected]])YD22iUM[%Oc');
if ( ! defined( 'NONCE_SALT' ) )
    define('NONCE_SALT', '|1.e9Tx{fPv8D#IXO6[&lt;WY*,)+7+URp0~|:]uqiCOzu93b8,h4;iak+eIN7klkrW');

/**
* 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 = 'ft_';

/**
* WordPress Localized Language, defaults to English.
*
* Change this to localize WordPress. A corresponding MO file for the chosen
* language must be installed to wp-content/languages. For example, install
* de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
* language support.
*/

define( 'WPLANG', '' );

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

if ( WP_LOCAL_SERVER || WP_DEV_SERVER ) {

    define( 'WP_DEBUG', true );
    define( 'WP_DEBUG_LOG', true ); // Stored in wp-content/debug.log
    define( 'WP_DEBUG_DISPLAY', true );

    define( 'SCRIPT_DEBUG', true );
    define( 'SAVEQUERIES', true );

} else if ( WP_STAGING_SERVER ) {

    define( 'WP_DEBUG', true );
    define( 'WP_DEBUG_LOG', true ); // Stored in wp-content/debug.log
    define( 'WP_DEBUG_DISPLAY', false );

} else {

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

Y aquí está el archivo de configuración local que mantengo un directorio por encima de la raíz de WordPress y esto también lo hace fuera del directorio accesible en la web, por lo que en caso de que Apache deje de analizar los archivos PHP y comience a tirarlos, nuestras credenciales de la base de datos aún son seguras ( enlace ):

<?php

/**
 * WordPress config file to use one directory above WordPress root, when awesome version of wp-config.php is in use.
 *
 * Awesome wp-config.php file - https://gist.github.com/1923821
 */

/* WordPress Local Environment DB credentials */

define('DB_NAME', 'project_21');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');

/* Keys & Salts */

define('AUTH_KEY',         '5H%)s-nQ,+fn0gwg/p1UjBTmCQ?l[8-!>Q{MW&?X3DM,OF;TaI<SOOTrl0+-@) *');
define('SECURE_AUTH_KEY',  '+%rr@,XIt-V+[.B9++uH1L,L+r)uq}5(:~=&4~Lk|.LV|y;R}fEo?G}+Sntf_JN}');
define('LOGGED_IN_KEY',    'Szv!gQm9#(L&TUD OnM'>sXGge:m1j'L2 5sO;hRNVhlN>IUED1/'%<[ly-GxVJ ');
define('NONCE_KEY',        'o-Jo;>G#-%~,[[email protected]%4^I.HDnc.3]P;e8];4pJt% $xe5K<aOb|a2*QKV4c-');
define('AUTH_SALT',        '8-tQb3d|W8,;Y_#mfuFB.1&b%U2fnlLD|F&yH).tLRX=ANEdNap{78o|9tqv6JPt');
define('SECURE_AUTH_SALT', 'RSa%^qd~T|@+!-;qgh,qK-GJ}zPpgxz#[email protected];BMwqT'TzGTtg_^n*ILxGOdbq4');
define('LOGGED_IN_SALT',   ']+XV)YK.Q-EU1vR [BT!Y$!d(J_[AO37OP[Fg[/esFx;6cI-L[^O|cvtw9F[;_*Q');
define('NONCE_SALT',       'iP{nTQBzy&f^hSbwBgyan.v9<+ErvAMi2ymLhz'Tl-fF?HXa(j<W'wA*8U3R#-|w');

De esta manera, si el archivo anterior se llama local-config.php , mi sistema se comporta como una instalación local. Si se llama staging-config.php , se comporta como una instalación provisional y si se llama production-config.php . Me ayuda a tener diferentes valores de ciertas constantes, como la depuración, tener diferentes valores en diferentes entornos y aún tener todo bajo SCM (git). Las posibilidades son infinitas y no se requiere ninguna piratería para diferentes entornos.

Esto asegura que nunca reveles ninguna información confidencial al público de todos modos y lo uso solo para comenzar cualquier proyecto en el que trabaje, tengo las claves más fuertes en su lugar de forma predeterminada y tan pronto como las agrego al segundo archivo de configuración En el directorio de arriba, esos se usan en lugar de los definidos aquí. ¡Bienaventurada!

    
respondido por el Ashfame 23.05.2012 - 11:07
9
  

¿Cómo puedo hacer esto sin exponer mis contraseñas a git, en caso de que este repositorio se vuelva público?

Si su archivo wp-config.php está en control de versiones, entonces cualquier contraseña que contenga también estará en control de versiones. La única forma de evitarlo es no poner el archivo en el control de versiones.

  

¿Esto es demasiado problema y debería dejar wp-config.php sin versión?

Mi intuición sería mantener completamente wp-config.php sin versión. Pero hay algunas formas de evitarlo.

Extraiga la parte de wp-config.php que contiene sus contraseñas y hashes en un archivo separado y include() en el archivo regular wp-config.php . Luego, coloque wp-config.php bajo el control de versión, pero mantenga su archivo include() separado.

wp-config.php :

<?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information
 * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don't have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 *
 * @package WordPress
 */

/** 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', '');

include( 'conf.php' );    

/**#@-*/

/**
 * 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 Localized Language, defaults to English.
 *
 * Change this to localize WordPress. A corresponding MO file for the chosen
 * language must be installed to wp-content/languages. For example, install
 * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
 * language support.
 */
define('WPLANG', '');

/**
 * 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.
 */
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');

Ahora puede ver que las contraseñas y los hash no están incluidos en wp-config.php en absoluto.

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


/**#@+
 * 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');

Pero honestamente, en este punto, solo estás agregando un nivel redundante de abstracción aquí. La razón por la que wp-config.php está separada en primer lugar es porque es específica del entorno. No deberías copiarlo de un servidor local a producción en absoluto ... por lo que no debería estar bajo el control de versiones en absoluto.

    
respondido por el EAMann 22.05.2012 - 18:39
4

El ejemplo de Mark supone que está trabajando con un repositorio privado:

if ( file_exists( dirname( __FILE__ ) . '/local-config.php' ) ) {
  include( dirname( __FILE__ ) . '/local-config.php' );
  define( 'WP_LOCAL_DEV', true ); 
} else {
  define( 'DB_NAME',     'production_db'       );
  define( 'DB_USER',     'production_user'     );
  define( 'DB_PASSWORD', 'production_password' );
  define( 'DB_HOST',     'production_db_host'  );
}

En lugar de definir las credenciales, puede crear fácilmente un archivo production-config.php e incluirlo dentro de la verificación condicional:

if ( file_exists( dirname( __FILE__ ) . '/local-config.php' ) ) {
      include( dirname( __FILE__ ) . '/local-config.php' );
      define( 'WP_LOCAL_DEV', true ); 
    } else {
     include( dirname( __FILE__ ) . '/production-config.php' )
    }

Luego, en tu versión-config.php sin versión:

  define( 'DB_NAME',     'production_db'       );
  define( 'DB_USER',     'production_user'     );
  define( 'DB_PASSWORD', 'production_password' );
  define( 'DB_HOST',     'production_db_host'  );
    
respondido por el Chris_O 25.05.2012 - 09:02
2

Podría cometer el archivo wp-config.php en el repositorio sin sus cadenas secretas y luego ejecutar:

git update-index --assume-unchanged wp-config.php

Esto le dirá a git que asuma que el archivo no ha cambiado, bueno.

    
respondido por el getWeberForStackExchange 26.05.2012 - 00:44

Lea otras preguntas en las etiquetas