Tag Archives: CentOS

Set Up Your WordPress Site to Use Password-Free SFTP For Better Security

This turns out to be a pretty easy trick to do. In order to accomplish this, you will need:

  1. to be able to ssh (or, heaven forbid, telnet) into a command line on your server and operate as root or a “sudoer”;
  2. to be able to edit the wp-config.php file for your WordPress installation;
  3. to be able to stop and restart your web server.

Assumptions: You’re running CentOS or something like it. If you’re running Debian, or something like it, you’ll need to use apt-get instead of yum, and your directory layout will be different.

Enabling SSH for PHP

We’re going to set up WordPress to enable uploads via SFTP; for that, we’ll first need to build and install the ssh2 extension to PHP. At your server’s command line, execute the following to load all of the infrastructure you’ll need:

$ yum install php-devel php-pear gcc gcc-c++ make automake autoconf pcre-devel re2c libssh2 libssh2-devel

Next, have pecl install the ssh2 extension.

$ pecl install ssh2-0.12

Turn on ssh2 by creating an ini file for PHP:

$ echo "extension = ssh2.so" > /etc/php.d/ssh2.ini

Restart your web server:

$ service httpd restart

At this point, the SSH2 PHP extension should be installed and activated; you can use

$ php -i | grep ssh2

to verify this.

Setting Up WordPress for SFTP

First thing to do is to generate a key pair. YOU MUST BE LOGGED IN AS THE USER WHO WOULD BE DOING THE UPLOADING TO WORDPRESS. At the command line, execute

$ keygen-ssh

When prompted to enter a file name, we’ll call the key pair “~/wp_rsa”, so as not to accidentally overwrite any other keys we have around. Once your key pair has been generated, execute the following commands in that user’s home directory:

$ cat wp_rsa.pub >> .ssh/authorized_keys
$ mv wp_rsa* .ssh/

For reasons that aren’t immediately clear to me, WordPress required both the public and private key to be available to it. Set the access protections appropriately:

$ chmod 755 .ssh/
$ chmod 644 .ssh/*

Next, edit wp-config.php, and add the following lines to the end, making the appropriate substitutions for your own site «where indicated»:

define('FTP_HOST', 'localhost');
define('FTP_USER', '«your user name goes here»');
define('FTP_PUBKEY', '«full path to user's home directory»/.ssh/wp_rsa.pub');
define('FTP_PRIKEY', '«full path to user's home directory»/.ssh/wp_rsa');

Finally, set the protections and ownership on the wp-content directory to allow Apache to create things in there (assumption — I have ownership of my wp-content directory set to «site owner»:apache; you may need to adjust this to suit your specific situation:

$ chmod 775 «full path to WordPress directory»/wp-content

You should be good to go.

[This posting is an adapted excerpt from the upcoming book “McFate’s Indispensible and Comprehensive Guide to Building Bullet-Proof Servers”]