How to Restrict User Access to Specific Directories in Linux

In many situations, you may need to restrict access to certain directories on your Linux system to protect sensitive data or prevent users from making unintended changes. In this blog post, we'll explore how to deny access to a specific user for a directory, using various methods. We'll take an example where the user devuser needs to be restricted from accessing the /var/www/project directory.

Why Restrict Access?

There are several reasons you might want to restrict access to a directory for specific users:

Let's dive into different methods you can use to restrict access.

Method 1: Modify Directory Permissions

The simplest way to prevent a user from accessing a directory is by modifying the directory's permissions.

Remove Permissions for the User: You can use the chmod command to change the permissions for the directory. However, this affects all users, so a more precise method is to use setfacl (Access Control Lists).
To remove all permissions (read, write, and execute) for the user devuser on the /var/www/project directory, use the following command:

sudo setfacl -m u:devuser:0 /var/www/project

Verify Permissions: You can check the permissions applied using the getfacl command:

getfacl /var/www/project

Method 2: Restrict Access via Apache (or Web Server)

If the access to the directory is through a web server like Apache, you can restrict access at the web server level.

Using .htaccess File: Create an .htaccess file inside the /var/www/project directory with the following content:

<Directory "/var/www/project">

    <RequireAll>

        <Require not user devuser>

    </RequireAll>

</Directory>

Editing Apache Configuration: Alternatively, you can add similar rules directly in your Apache configuration file (e.g., httpd.conf or within a virtual host configuration).
<Directory "/var/www/project">

    <RequireAll>

        <Require not user devuser>

    </RequireAll>

</Directory>

After making the changes, reload Apache to apply the new rules:

sudo systemctl reload apache2

Method 3: Using SELinux or AppArmor (Advanced)

For systems using SELinux or AppArmor, you can create specific security policies to restrict access. This method is more advanced and provides stronger enforcement.

Conclusion

Restricting access to directories in Linux is essential for maintaining security and protecting sensitive data. By using the methods described above, you can easily prevent specific users from accessing directories, whether through direct file system access or via web servers.

Choose the method that best suits your needs, and remember to test the restrictions to ensure they work as expected.