Monolune

How to Connect from WordPress to MySQL using SSL

If you have a WordPress installation on one system, and a MySQL or MariaDB database server on another system, you may want to ensure that the data transfers between them are secure. SSL can be used to prevent eavesdropping and tampering on data. This guide will show the steps needed to configure WordPress to connect to MySQL using SSL.

Assumptions

This guide assumes that:

  • You already have a self signed SSL CA certificate.
  • You are on Linux.
  • The PHP installed on the system running WordPress uses Mysqlnd (MySQL native driver) as the driver for MySQLi. Note that this is the default for new PHP installations.

Configure WordPress

First, attempt a remote connection to the MySQL or MariaDB server to make sure that remote connections using the SSL certificate works:

# On the command line, run:
mysql --user john --host db.example.com --ssl-ca my-ca.crt --password

If you were not able to connect to the database, you must first fix the issue that prevents the connection. If you were able to connect, you can now add your self signed SSL certificate to OpenSSL's trusted store:

# On the command line, run:
sudo mv my-ca.crt /usr/local/share/ca-certificates/
sudo update-ca-certificates

Important: The file name of the certificate must only end with a crt extension. my-ca.crt is fine, but my-ca.pem.crt and my-ca.pem are invalid!

Next, verify that PHP is able to connect to the database using SSL. Start the interactive PHP shell by running php -a. Then:

// In the interactive PHP shell:
$db = mysqli_init();
mysqli_real_connect($db, 'db.example.com', 'john', '123456', NULL, NULL, NULL, MYSQLI_CLIENT_SSL);
var_dump(mysqli_query($db, 'STATUS;'));  # Should show results, not false.

If there are errors in the interactive shell, you must resolve them. If all goes well, you can now set the appropriate settings in the wp-config.php file of your WordPress installation:

// In wp-config.php, add:
define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL);

At this point, WordPress should connecting to the MySQL server through an SSL connection.

Discussion

As far as I am aware, the method outlined above is the simplest way to get secure connections between WordPress and the database, Other SSL methods I have looked at involve patching the WordPress source code, which is not something that most people would recommend. An alternative to SSL is to establish a persistent (permanent) SSH tunnel between the system running WordPress, and the system running the database server. While this works, both anecdotal evidence and unscientific tests have shown that is option is slower than using SSL.