How to Setup SFTP on CentOS/RHEL/Amazon Linux 2

All actions will also be relevant for CentOS/RHEL systems. In this example, a user will be added for access via SFTP using an SSH key to the web directory under Apache management. There is a default for Apache group “apache“, if necessary, replace the desired one.

All sites are on the dir:

1

/var/www/html

Add the user sftpuser (already in the existing group):

1

useradd-gapache-d/var/www/html-s/sbin/nologin sftpuser

Let’s give the group rights to write, since we will change the owner:

1

chmod-Rg+w/var/www/html/*

Change the ownership of files:

1

chown-Rsftpuser:apache/var/www/html/*

The “html” directory itself should not belong to the “sftpuser” user

Create a directory for public keys and give it the necessary rights:

1

mkdir/var/www/html/.sshchmod700/var/www/html/.ssh

In this directory, create two files and place the public SSH key in them:

1

authorized_keysid_rsa.pub

Set the necessary rights to the file:

1

chmod644/var/www/html/.ssh/*

Making the user sftpuser owner:

1

chown-Rsftpuser:apache/var/www/html/.ssh

Open the SSH server configuration file:

1

vim/etc/ssh/sshd_config

Replace the string:

1

Subsystem sftp/usr/libexec/openssh/sftp-server

On the following:

1

Subsystem sftp internal-sftp

And add the following block to the end of the file:

1

2

3

4

5

Match Group apache

X11Forwarding no

AllowTcpForwarding no

ChrootDirectory%h

ForceCommand internal-sftp

Reboot the SSH service:

1

service restart sshd

We connect via SFTP client by specifying the username “sftpuser” and the path to the private SSH key, on the basis of which the public one was generated, the port for connection is SSH port (by default 22).