Configure SFTP for Web Server Document Root (Ubuntu and Debian)

A vibrant orange server tower with a file securely routing into a specific root folder. Text: SFTP DOCUMENT ROOT.

We may earn a referral fee at no additional cost to you when you shop through the links on this page.

You want to give a developer or client SFTP access to your web server’s document root without granting shell login or running a second daemon. This DevAnswers guide walks the modern OpenSSH recipe: an SFTP-only user chrooted to /var/www, covering the chroot ownership trap that catches almost everyone the first time.

Prerequisites 

  • SSH access with sudo on the target Ubuntu or Debian server.
  • OpenSSH server already installed and running. Confirm with systemctl is-active ssh.
  • A web server (Apache or Nginx) configured with a document root, typically /var/www or /var/www/html.
  • Permission to edit /etc/ssh/sshd_config and reload the SSH service.
  • A local SFTP client to test: command-line sftp, FileZilla, or WinSCP. If you are new to SSH from a Linux client, our guide on connecting to a Linux server with SSH covers the entry point.

What This Setup Builds 

The end state is a Linux user account that can connect via SFTP and upload to your web server’s document root, but cannot log in to a shell, is confined to the chroot directory (it cannot navigate outside /var/www on the host), and cannot tunnel other services through the SSH connection. There is no separate FTP daemon to install, configure, or harden. SFTP rides on top of your existing SSH service. The pattern works for one user or a small team. If you are looking for the FTP-daemon alternative for a similar use case, our sister guide on vsftpd 550 Permission denied covers the FTP-stack version of the same problem.

Install or Confirm OpenSSH Server 

Most cloud images on Ubuntu and Debian ship OpenSSH preinstalled and running. Confirm before changing anything:

Terminal
sudo dpkg -l openssh-server
systemctl is-active ssh

The systemd unit on Ubuntu and Debian is called ssh.service; some documentation refers to it as sshd, which is the daemon binary name but not the unit name on Debian-derived systems. If openssh-server is not installed, install it before continuing:

Terminal
sudo apt update
sudo apt install -y openssh-server

The directives this guide uses (ChrootDirectory, ForceCommand, Match Group, internal-sftp) are supported on all five tested target platforms: Ubuntu 22.04, 24.04, 26.04 and Debian 12, 13. The exact OpenSSH version your distro ships is captured in the test badge near the top of this article.

Create the SFTP-Only User 

Create a Linux user with a non-interactive shell so they cannot SSH in for a shell session, and add them to a dedicated group that the SFTP-only sshd rules will match on. Replace sftpuser with the actual username you want.

Terminal
sudo groupadd sftponly
sudo useradd -m -G sftponly -s /usr/sbin/nologin sftpuser
sudo passwd sftpuser

The -s /usr/sbin/nologin flag gives the account a non-interactive shell. If a normal SSH login is attempted, the user is rejected with a message like “This account is currently not available.” Combined with the ForceCommand internal-sftp directive in the next sshd rule, shell access is denied at two layers, so even a configuration drift on the group membership cannot accidentally hand the user a shell. For a deeper walkthrough of the lockdown recipe, see our companion guide on denying shell access to FTP users.

If you want password authentication for first-test simplicity, the passwd command above sets it. For production, prefer SSH key authentication. Place the user’s public key in /home/sftpuser/.ssh/authorized_keys (mode 600, owned by the user) and you can disable password auth later inside the Match block. If your client is on Windows, our guide on PuTTY SSH key authentication covers the keypair-generation walkthrough for that side.

Set Up the Chroot Directory: The Ownership Trap 

This is the section that catches almost everyone the first time. OpenSSH refuses to enter a chroot if any component of the chroot path is writable by anyone other than root. The check is strict and unconditional. From the sshd_config manual page:

At session startup sshd(8) checks that all components of the pathname are root-owned directories which are not writable by group or others.

If you point ChrootDirectory at a path where any component is owned by a non-root user, or has group or world write permission, sshd writes fatal: bad ownership or modes for chroot directory component to the systemd journal (visible via journalctl -u ssh) and refuses the session. The reader sees “Connection closed by remote host” or “Received message too long” on the SFTP client side, and the session dies before transferring any data.

The resolution has two parts. First, make the chroot root non-writable by anyone except root. Then, create a writable subdirectory inside the chroot that the user owns. This preserves the security model while still giving the user somewhere to upload.

Terminal
# The chroot root: owned by root, not writable by anyone else
sudo chown root:root /var/www
sudo chmod 755 /var/www

# A writable subdirectory the user can actually upload into
sudo mkdir -p /var/www/html
sudo chown sftpuser:www-data /var/www/html
sudo chmod 2775 /var/www/html

The 2775 mode on the upload subdirectory matters. The leading 2 sets the setgid bit, which makes any new file created inside the directory inherit the directory’s group (www-data) rather than the SFTP user’s primary group. Without setgid, new files would be owned by sftpuser:sftpuser and Apache or Nginx (running as www-data) would not have read access to them.

Verify the structural pattern before you move on. The chroot root must show as drwxr-xr-x root root (or stricter), and the writable subdir must be owned by the SFTP user and the web-server group with the setgid bit set:

Terminal
stat -c '%A %U:%G %n' /var/www /var/www/html

Note that every parent component of the chroot path must also be root-owned and non-writable by others. /var/www requires /var and / to also pass the check, which they do on a standard install. If you are chrooting to a non-standard path (for example, /srv/uploads with custom parents), run the same chown root:root + chmod 755 pattern on every component up to /.

Configure sshd_config with Match Group 

The SFTP-only rules go inside a Match Group block at the end of /etc/ssh/sshd_config. The placement matters: a Match block scopes everything that follows it until the next Match block or the end of the file. Adding it at the end keeps the global directives above it untouched. Open the config file:

Terminal
sudo nano /etc/ssh/sshd_config

Scroll to the bottom and append the following block:

/etc/ssh/sshd_config
Match Group sftponly
    ChrootDirectory /var/www
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no
    PasswordAuthentication yes

Each directive does specific work. ChrootDirectory /var/www tells sshd to enter the directory you set up above as a chroot jail. ForceCommand internal-sftp activates the in-process SFTP subsystem, which means no external sftp-server binary needs to exist inside the chroot. AllowTcpForwarding no and X11Forwarding no prevent the user from tunneling other network services through their SSH connection. PasswordAuthentication yes is set inside the Match block for first-test simplicity; switch it to no once you have key authentication working.

Place the Match block at the END of sshd_config. A Match keyword scopes every directive that follows it. If you put it in the middle of the file, all the global directives below it become conditional on the Match instead of applying server-wide. Test with sudo sshd -t before reloading to catch config-syntax errors.

Reload SSH and Test the Setup 

Reload sshd so it picks up the new Match block. Use reload rather than restart so existing SSH sessions stay connected (the new config takes effect for new sessions only):

Terminal
sudo sshd -t  # syntax check first
sudo systemctl reload ssh

Now verify from a client. From your local machine (or another server), test the SFTP login and confirm shell login is refused:

  • Connect via SFTP: sftp sftpuser@your-server. You should land at the root of the chroot (/ inside the chroot, which is /var/www on the host).
  • Change into the writable subdir: cd html should succeed.
  • Upload a test file. First create one outside the SFTP session on your local machine: echo "hello" > /tmp/test.txt. Then back in the SFTP session: put /tmp/test.txt test.txt (the second argument is the remote filename; the explicit form avoids the standard ftp client gotcha of using the full local path as the remote name).
  • Confirm shell login is refused: ssh sftpuser@your-server from your local machine should be rejected with a message about the account not being available, or the connection closing immediately.
  • From the server side, verify the uploaded file: ls -la /var/www/html/test.txt. It should show ownership sftpuser:www-data and the mode determined by the SFTP client’s umask.

Scaling to Multiple Sites or Users 

The recipe above works for a single SFTP user chrooted to one document root. If you are running multiple vhosts, an agency setup with several client sites, or just want a separate SFTP account per site, OpenSSH supports the %u token in ChrootDirectory, which expands to the username at session start. One Match Group block then serves any number of users without duplication.

One constraint to know up front: because %u expands to the Linux username, the chroot directory name has to match the username. That works well if your usernames are short identifiers tied to each client or site (for example, acme for acme.com, or generic site1, site2). If you really want fully domain-named directories like /var/www/example.com/, jump to the per-user Match User alternative below.

Lay out one chroot per site under /var/www with the same ownership pattern as before: chroot root owned by root:root and mode 755, plus a writable subdirectory owned by the per-site user. Using three client tenants named acme, widgetshop, and bobsite as an example:

Paste the following block into the terminal. It creates all three users plus their per-site chroot directories in one go. The useradd command does not set a password, so the loop runs non-interactively from start to finish.

Terminal
for u in acme widgetshop bobsite; do
  sudo useradd -m -G sftponly -s /usr/sbin/nologin "$u"
  # Per-user chroot root: owned by root, non-writable by anyone else
  sudo mkdir -p "/var/www/$u"
  sudo chown root:root "/var/www/$u"
  sudo chmod 755 "/var/www/$u"
  # Writable subdir the user actually uploads into
  sudo mkdir -p "/var/www/$u/html"
  sudo chown "$u:www-data" "/var/www/$u/html"
  sudo chmod 2775 "/var/www/$u/html"
done

Set credentials per user separately. For SSH key authentication (recommended for production), drop each user’s public key into /home/<user>/.ssh/authorized_keys with mode 600 and ownership matching the user. For password authentication, run sudo passwd once per user:

Terminal
sudo passwd acme
sudo passwd widgetshop
sudo passwd bobsite

Then update the Match block at the end of /etc/ssh/sshd_config to use the %u token. The single block now handles every member of the sftponly group, chrooting each user into their own directory:

/etc/ssh/sshd_config
Match Group sftponly
    ChrootDirectory /var/www/%u
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no
    PasswordAuthentication yes

Reload sshd with sudo systemctl reload ssh and each user connects with their own credentials. They land in their own /var/www/<username> chroot, see only their own html/ directory as writable, and cannot navigate into another user’s site or anywhere else on the host. Adding a new client later is straightforward: create the user with one iteration of the loop above, set their credentials (password or SSH key), and that is it. No sshd reload required because the existing Match block already covers them by group membership.

Map this layout to your web server’s vhost configuration. For Apache, each vhost’s DocumentRoot points to /var/www/<username>/html. For Nginx, the equivalent root directive in each server block. The shared www-data group membership ensures Apache and Nginx can read the uploaded files regardless of which SFTP user wrote them.

If you specifically need domain-named chroot directories (for example, /var/www/example.com/ to match an existing layout where vhost directories already include the dot in the name), the %u shortcut does not work. Linux usernames cannot contain dots, so the directory name cannot equal the username. Use a per-user Match User block with a hardcoded path instead:

/etc/ssh/sshd_config
Match User acme
    ChrootDirectory /var/www/acme.com
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no

Match User widgetshop
    ChrootDirectory /var/www/widgetshop.co.uk
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no

This trades the single-block elegance for explicit per-user paths. Each new client adds a fresh Match User stanza and an sudo systemctl reload ssh. The chroot ownership pattern is identical: /var/www/example.com/ owned by root:root mode 755, with a writable html/ subdirectory owned by the SFTP user. Most agency operators stick with the %u approach and short tenant usernames; the Match User alternative is mainly for retrofitting onto an existing layout you cannot rename.

Troubleshoot Common Errors 

The canonical chroot error appears in journalctl -u ssh (and in /var/log/auth.log if rsyslog is installed; on Ubuntu 24.04+ and Debian 12+ rsyslog is no longer installed by default, so journalctl is the only surface) and reads:

journalctl -u ssh output
fatal: bad ownership or modes for chroot directory component "/var/www"

The message names a specific path component. The most common case is that the path itself is writable by a non-root user or group. Check the full path tree:

Terminal
stat -c '%A %U:%G %n' / /var /var/www

Every component must show drwxr-xr-x root:root (or stricter; group or other must not have w). If any component is owned by a non-root user or has group or world write permission, fix it with sudo chown root:root and sudo chmod 755. The fix must be applied all the way up to /, not just on the immediate chroot path.

For other failure patterns, the standard diagnostic surface is sudo journalctl -u ssh --since "10 minutes ago" on every modern Linux distro. If your system still ships rsyslog (Ubuntu 22.04 and earlier; Debian 11 and earlier), sudo tail -n 50 /var/log/auth.log shows the same sshd events. Most chroot or Match-block misconfigurations produce specific, searchable log lines.

Next Steps 

Once the setup works, three follow-ups are worth considering. First, switch the Match block’s PasswordAuthentication directive to no once you have SSH keys working, so the SFTP-only account can only authenticate with a key. Second, add fail2ban to block repeated failed-auth attempts on the SSH service. Third, monitor SSH authentication events regularly via journalctl -u ssh for unfamiliar source IPs attempting your SFTP user account; the audit trail is the first place an intrusion shows up. For teams that would rather not maintain SSH plus SFTP plus chroot configuration themselves, a managed hosting platform such as Cloudways handles the file-transfer plumbing alongside the application stack.

Support DevAnswers
Written, tested and maintained by one developer. Your support keeps these guides accurate and ad-light.
Buy me a coffee

58 replies

Leave a reply

  1. Do Hoang

    Hello,
    Thanks for your blog, it works well with chroot folder /var/ww/
    But what if I have multiple user, and i want each user chroot into their own folder
    My folder structure is:
    /var/www/html/website1
    /var/www/html/website2
    …
    what configuration should i use and is this possible?

  2. Deeptesh

    Just amazing awesome. This is exactly I was looking for.
    Its just that this page was not coming up on google search engine with “configure sftp on linux”

    1. DevAnswers

      Thanks. I added the phrase How to configure SFTP on Linux into the meta description 😉

  3. kribo

    Hi,
    How do I create a ssh user for github with restricted access to a one documentRoot
    thnx

  4. Markus

    Me again 🙂
    I figured it out. It was just my missunderstanding.
    I added the domain name as a folder and added html inside that folder, then I made the domain folder the chroot and added -d /html to ForceCommand internal-sftp

    Now it works as I thougt it would.
    Thanks for the great tutorial. Saved me a lot of time!

  5. Marksu

    For Method 2: I followed the steps and can login on the server, create, delete folders or files in the configured DocumentRoot.
    Maybe it’s a missunderstanding on my part, but when I log in I can see all DocumentRoots and I thought the sftp user will only see its DocumentRoot. I cannot create a new folder or delete one in the other DocumentRoots, but I can create files or look at the other files.
    Is there a way to prevent this and make sure that the sftp user has only access to its DocumentRoot
    I redid all the steps and I am sure I followed everything.
    Chroot: /var/www/
    DocumentRoot of sftp_user1: /var/www/domain1

    There are several other domains under /var/www/

    I hope it’s clear what I mean since English isn’t my first language.

    Kind regards,
    Markus

  6. Dan Morton

    Method Two (Section 5) did not work for me, until I added sftp_users to AllowGroups and yyyyy to AllowUsers in /etc/ssh/sshd_config. The omission of either prevents access; the inclusion of both gets me in. But I did not see any reference to this in the article.

  7. Dan Morton

    I’m using Method Two (Section 5), and yyyyy is my account name for my virtual host (/var/www/54plymouth.net). I’m using WinSCP from my desktop to access my server, but I’m getting “Access denied” after I supply the password. /var/log/auth.log reports “User yyyyy from x.x.x.x not allowed because not listed in AllowUsers”. I’ve defined my ssh login in /etc/ssh/sshd_config in AllowUsers, but I don’t see any mention in this article of a similar requirement for sftp users. Should I add yyyyy to AllowUsers, or is this an indication that I’ve missed a step somewhere?

  8. George Young

    Thanks you SO MUCH for this tutorial. I spent hours searching for how to do this properly and yours is the only article I could find that got me through the process. I’ve also learned a lot about how to think about server security in the process. If, by some amazing chance, we ever meet, I owe you a beer.

  9. Mac_PL

    Dear DevAnswers. I have got VPS on Debian 9 with Apache2 and SSH. I set up two virtual hosts. One is, for example, /var/www/html/domain1.com/. I will install WordPress there. I have to add sftp user. My question is, is it benefitial (especially from security point of view) to add sftp user with home directory in /var/www/html/domain1.com/ ? Instead of creating normal user with home directory in /home/user_name. If this sftp user is only for maintaining WordPress, then also for sake of order, isn’t it better to make his home directory in /var/www/html/domain1.com/ ? Thanks in advance for your reply.

    1. DevAnswers

      My recommendation would be to leave the home folder in the default location /home/.

      The SFTP user doesn’t need access to their home folder and they can’t log in over SSH, that’s why we have ForceCommand internal-sftp; in the SSH config to force SFTP access only.

  10. Jürgen

    Just what I needed.

    My server was hacked because chroot was owned by www-data – NEVER AGAIN

  11. Andrew

    Brilliant, worked perfectly

  12. Jeeva

    Thanks for this great article. As I am learner and very new to web development and also on linux. After I successfully configured following Method One of this article I installed fileZilla on my ubuntu 18.04 LTS os but failed to connect to my web server. ( I used my Server’s IP, my SFTP username and password on FileZilla)
    After login attempt is reflects –
    Response: 530 Login authentication failed
    Error: Critical error: Could not connect to server

  13. bazkie

    thanks! great explanation, worked wonders for me

  14. alam

    Found an error in the sshd log:
    sshd error: /dev/pts/0: no such file or directory

    After this session closes.

    1. statuscue

      I am getting this same error. However, the problem did not present itself until recenstly and I followed the changes in this article months ago.

      1. DevAnswers

        Is this preventing SFTP login or just SSH?

        You cannot log in through SSH using the SFTP user, that’s diabled with ForceCommand internal-sftp; in the SSH config.

  15. alam

    Great article, thank you. After I successfully configured this following Method Two, I can no longer open an SSH session using PuTTY from windows – the console closes right after the credentials are entered. Any idea what might have caused this?

    1. shank

      I also faced this. You have found any solution ? please tell me

  16. Mr Vincent Gledhill

    Thanks for your great website. I have used it many times sorting out my server. I have followed this guide to the letter and still can’t connect. I have multiple sites on the server running apache, all with wordpress installed. I have only tried the less secure method but am getting a Connection refused
    Error: Could not connect to server error message.
    Any ideas?

  17. Zorann

    I was so happy when I made yesterday everything work, yet I encountered a serious problem. I had SFTP with multiple virtual hosts, and I was using FileZilla to copy files on each one. Yet i forgot to add sftp_users as owner to one of virtual hosts, and couple dozens mkdir could not be executed, and the transfer took a long while.
    Meantime I was typing command on mu ubuntu server and keyboard suddenly stopped working. The underscore line was blinking whole time, but I wasn’t able to type anything. After few minutes I hit enter few times, typed shutdown (or reboot), press enter and wait… and the server executed the command!

    Ok, I tought that everything is fine, but now I’m unable to connevt to sftp. Filezilla returns FATAL ERROR: Network error: Software caused connection abort.
    I have no idea what to do now. I tried redo all the steps multiple times, checked virtual hosts settings and tried to redo them as well, nothing works. What can be the problem? I’d like to provide more informations or some logs, but I don’t know where could i get some. Can You help me?

    1. DevAnswers

      Sorry to hear you’re having issues.

      The FileZilla error sounds like it is just not seeing any SFTP service on your server, so you should start troubleshooting that issue first.

      Are you remotely connected to your Linux box via SSH or physically at the machine with keyboard?

      I’d firstly try a port scan of your IP to see if it’s seeing SSH port 22 (which SFTP uses). There are several tools online for that.

      Any errors in your SSHD config?

      sudo sshd -t

      Also make sure to completely close FileZilla and open it again after making any permissions changes in Linux. Sometimes this is the only way to force FileZilla to log out and in again.

      1. Zorann

        sudo sshd -t returns no error. Only without sudo it returns sshd: no hostkeys available -- exiting.

        I rebooted both server and my PC just to be sure, but problem stays. I’m trying to connect to server from windows PC.

        Online scan shows that port 22 is open on my IP.

        It’s not FileZilla-only problem, because I’m using as well Notepad++ with ftp addon and it does return such thing:
        Connecting [SFTP] Host key accepted [SFTP] Successfully authenticated [SFTP] Error initialising channel: Socket error: Unknown error Unable to connect Disconnected

        So it does look like it does connect and error shows up later. Are there any log files of that attempt on server that can help identify the issue? I’m almost sure that I messed something up while tryint to reconfigure virtual hosts, but I’m unable to find error.

        And it did totaly worked before… Yet I might mess up something while I was setting up virtual hosts and trying to redo the guides. However I’m unable to find error, even if it might be something obvious for more experienced user.

        Thank You in advance for Your time!

      2. Zorann

        Some additional info: it does look like ssh connection does not work after all. My ubuntu server local IP is 192.168.1.5, and my windows pc does have 192.168.1.3.

        First I tried cmd on windows:
        telnet 192.168.1.5 22, and such line occurs:
        SSH-2.0-OpenSSH_8.2p1 Ubuntu-4, but when I press enter, it returns Invalid SSH identification string., and Connection with host was interrupted (the second one is my translation, not original message).

        Than I tried on Ubuntu server:
        telnet 192.168.1.3 22, and it ends up on Trying 192.168.1.3... untill it is timed out.

        So it looks like after all the connection is not established at all. Windows does know that he is connecting to ubuntu, so there is “some” connection, but I know to little to judge that…
        I tried to repeat all instructions from points 1 and 2, but it does not fix issue. Reboot does not help as well. What could be the reason?

        1. DevAnswers

          Can you check your auth log to if there is any more info there? This will return the last 50 entries:

          sudo tail -n 50 /var/log/auth.log

          Also, I’m wondering could this be related to the sshd: no hostkeys available -- exiting error. Have you done a search on how to generate these hostkeys in Ubuntu?

          I would also download PuTTY for Windows and see if you can connect to the Ubuntu server using your root account. https://devanswers.net/log-linux-windows-using-putty/

          1. Zorann

            I was not able to find a solution for sshd: no hostkeys available — exiting. Yet it does work previously regardless of that error. I’d like to get rid of it just to be sure, but I wasn’t able to do so.

            Putty connection attempt ended with error:
            Network Error: Software caused connection abort

            The auth.log indeed gives additional information. This raport does look the same for every connection attempt for FileZilla, Notepad++, or Putty, and looks like this:

            sshd[13413]: Accepted password for ftp_username from 192.168.1.3 port 49728 ssh2
            sshd[13413]: pam_unix(sshd:session): session opened for user ftp_username by (uid=0)
            systemd-logind[842]: New session 10 of user ftp_username.
            sshd[13483]: fatal: bad ownership or modes for chroot directory component “/var/www/”
            sshd[13413]:pam_unix(sshd:session): session closed for user ftp_username

          2. Zorann

            (had some troubles with posting my answer, hope it didn’t spam You, heres the rest of my message):

            In sshd_config I set ChrootDirectory /var/www/example.com/, but I’m not sure how it should be set if I use as well /var/www/example2.lan/ and /var/www/example3.lan/? I don’t remember the setthings that I had when it worked for a while…

            Meantime tried to set ChrootDirectory /var/www/ so it could work for all at once, but guess it doesn’t work like that. since it’s not directly above public_html. I even and set privilages from 5.4. Set Document Root Permissions for /var/www/ – perhaps that was my mistake? If so – I don’t know how to fix it.

          3. DevAnswers

            PuTTY won’t work for your SFTP accounts, but can you log in using your Linux root account just to confirm SSH is working correctly?

            It really sounds like a permissions issue. It’s probably the most tedious part of setting this up as SFTP is really picky about directory permissions and ownership.

            I can give you the permissions for my own setup (Using Method Two). You should compare your ones and make sure they are similar.

            sudo ls -la /var/www
            drwxr-xr-x 15 root     root     4096 Mar  6 00:28 .
            drwxr-xr-x 15 root     root     4096 Feb 13  2019 ..
            drwxr-xr-x  3 root     root     4096 Feb 19  2019 devanswe.rs
            sudo ls -la /var/www/devanswe.rs
            drwxr-xr-x  3 root root                4096 Feb  8 20:26 .
            drwxr-xr-x 13 root root                4096 Mar 26 17:20 ..
            drwxrwsr-x  7 root sftp_devanswers_co  4096 May  7 06:04 public_html
            sudo ls -la /var/www/devanswe.rs/public_html
            drwxrwsr-x  7 root         sftp_devanswers_co   4096 May  7 06:04 .
            drwxr-xr-x  3 root         root                 4096 Feb  8 20:26 ..
            -rw-rw-r--  1 root         sftp_devanswers_co   198 May 18 22:53 .htaccess
            -rw-rw-r--  1 root         sftp_devanswers_co   405 Apr  1 13:55 index.php

            SSHD config entry:

            Match Group sftp_devanswers_co
                    ChrootDirectory /var/www/devanswe.rs/
                    ForceCommand internal-sftp
                    X11Forwarding no
                    AllowTcpForwarding no
                    PasswordAuthentication yes
          4. Zorann

            I just realized how retarded I was when I dive under my desk to server instead of using Putty in the first place… You helped my SOOOO MUCH! Anyway: Putty SSH connection worked and I was able to login as root.

            Finally after altering chmod and chown I made it! I wasn’t able to reproduce all Your permissions 100% the same, because there was something like this:

            sudo ls -la /var/www
            drwxr-sr-x  3 root root 4096 maj 30 13:36 .
            drwxr-xr-x 14 root root 4096 maj 26 20:57 ..
            drwxr-sr-x  3 root root 4096 maj 27 19:05 test.com

            I tried various things to change drwxr-sr-x into drwxr-xr-x, but after I tested my setting and ftp connected I decided not to touch it anymore for now. Now I’ll have to set all my virtual hosts again from scratch because I removed them to make things simple again. Guess that I’ll reconnect FTP after every step just to know when I mess up sumething just to be safe.

            Thank You so much!

          5. DevAnswers

            Thanks for the feedback as it helps me improve these guides.

            The error you mentioned when viewing the auth log sudo tail -n 50 /var/log/auth.log

            fatal: bad ownership or modes for chroot directory component “/var/www/”`

            I came across this error today when I was setting up SFTP.

            This is due to the permissions and ownership of the chroot directory, which SFTP is very picky about. So it should be noted that:

            • The chroot directory and all of its parents must not have group or world write capabilities. In other words, you must make sure /var/www/ is set to 755. (not 775, which gives group write permissions).
            • The chroot directory and all of its parents must be owned by root.

            I have updated the article to clarify this.

  18. Karim Hosein

    It worked right up until I did the “match user” thing, then I started getting this message.

    ssh_init: Name or service not known
    Could not connect to server

    So I removed the code block from the config, but it still gives this error. I cannot get back to how it was before, even after complete reboot.

    1. DevAnswers

      That’s strange. Do you get any error when running sshd -t?

      Are you behind a firewall, can you connect ok via SSH?

      1. Zorann

        After sshd -t part i get sshd: no hostkeys available -- exiting.

        However i tried sudo sshd -t and there was no error.

        Is something wrong?

        1. DevAnswers

          There must be some permissions issue going on there but I think it can be ignored. I’ve updated the guide to include sudo.

  19. Arvind Kumar

    Could be a good guide but its “Generate a password and press enter to accept all defaults.” where it broke!

    1. DevAnswers

      What happened at that point?

  20. Andrew

    Great!

    Thank you very much!

    This saves me a lot of time!

    I was looking for how to install vsftpd… this was easier and better.

  21. cakra

    great and detail explanation
    working at the first try.

    Kudos for you mate!

    thanks a lot

  22. James

    Amazing Tutorial!! Worked the first time 🙂 Keep up the great work

    James

  23. Gary

    So, normally I have had Apache:Apache as ownership in my web directory. Now a test file transferred to the web root is user:user. Will this be accessible to the website? Did I miss something?

    1. Arvind Kumar

      Did you find an answer, I face the same issue. If I change it to webdev my website breaks!

      1. DevAnswers

        Make sure that www-data can read and execute files in your doc root.

        I am currently re-writing this guide to clarify this and should have it up in a day or so.

  24. annas

    Great explanation. I’ve also seen some posts disabling login for the ftp user…

    usermod -s /usr/sbin/nologin myuser

  25. K Tysinger

    This is the finest LAMP tutorial I have ever read on the Internet. It actually works and it is clear that you spent a whole lot of time writing this. You are a master of LAMP. Thank you!

    1. DevAnswers

      👍🧐

  26. Yuri

    At last! Clear and understandable instructions!

  27. Hugo

    Excellent guide. Finally I have found what I looking for (paraphrasing Its U2’s song…). You help me a lot!!!.
    Many thanks and greetings from Argentina,

    Hugo

    1. DevAnswers

      Saludos desde Irlanda 🎸

  28. Frank

    Probably the best guide on the net about SSH setting …. incredible work!

  29. Dave Smith

    Something I don’t understand about your instructions, and I’m a learner so I don’t want to say YOU’VE GOT IT WRONG when it is much more likely that I’m misunderstanding something, so please correct me!
    (By the way, having to exclude code from my feedback because with code, getting blocked by cloudflare)

    But, as I understand it
    SFTP protocol explicitly depends on the user having SSH. To be denied an SSH login is to be denied an SFTP login.

    So Step 1.3 is to “(…) restrict the user (…) to the document root and also disable their SSH access – we only want them to be able to log in over SFTP.” and that contradicts what I understand about SFTP.

    Experience bears this out; If I include the line (code broken up to allow without cloudflare having a hissy fit) Fo rc eC om ma nd inte rn al-sf tp in my file /e tc/ss h/s shd _con fig , I can’t log in with FileZilla. If I comment it out and reload sshd then filezilla works over sftp.

    1. Dave Smith

      Scratch all that, something else was preventing me from logging in.

  30. Nick

    I first followed this to try a single user with access to an experimental directory. It worked fine. Then I wanted to try adding a user to a group, and setting up the group access like you described in part 2. I was able to get the user to log in and navigate all through the folders down from the chroot, but I get a permissions denied message when trying to upload files to any of the directories.

    1. DevAnswers

      So you should check the permissions for the directory and make sure they are set to the correct group. e.g:

      ls -ld /var/www/html
      
  31. James Pike

    I followed this tut yesterday, and everything was working fine, except none of the users I created had access to upload anything to the server.

    So after reading more about permissions and groups, I changed some permissions settings. Restarted the server, and now I can’t connect at all. Running FileZilla on the server computer, gives the error:
    Error: Connection reset by peer
    Error: Could not connect to server

    From any of my other computers, I get:
    Network Error: Software caused connection to abort.

    Any ideas, what happened, an/or how to fix it?

    1. DevAnswers

      Are you able to SFTP in using your root or sysadmin account?

      1. James Pike

        I decided to double check the newest parts I added to the sshd config, and compared it to items listed in this tutorial, and discovered I had a couple errors. Basically, the chroot was wrong for my sites. I had it set for var www mydomain.com public_html. Once I removed the public_html, from the end of each entry, I was able to log in again, and upload files.

        However, in the process, I discovered one of my sites is not functioning at all. And giving a error 500: This page isn’t working
        masterbuddasartgallery.com is currently unable to handle this request.
        HTTP ERROR 500.

        I’m thinking it’s due to the old server it was hosted on was using Apache. and I’m now using Nginx. So looking into how to transfer it over. Already set the database up for it, so that part “should” work. LOL

      2. Sam

        Yes root access is still working