How to Change Ownership Root to Apache?

Apache, formally known as the Apache HTTP Server, is one of the most widely used web server software systems in the world. Changing ownership of files from root to Apache is often necessary for web servers like Apache to have the correct permissions to read, write, and execute files. This is essential for the proper functioning of a web server and to enhance security by ensuring that the web server operates with the least privilege necessary.

There are primarily two approaches to changing ownership from root to Apache which are as follows:

Table of Content

  • Using the chown(change ownership) Command
  • Using chown with Recursive Option

Using the chown(change ownership) Command

The chown (change ownership) command in Unix-based systems allows you to change the owner and group of a file or directory.

Steps:

1. Open the Terminal: Access your server’s terminal through SSH or directly.

2. Navigate to the Directory: Use the cd command to navigate to the directory containing the files you want to change ownership for.

cd /path/to/directory

3. Change Ownership of a Single File: Use the chown command to change the ownership.

sudo chown www-data:www-data filename
  • www-data:www-data specifies the new owner and group for the files
  • filename is the name of the file you want to change ownership for.

Example:

  • Initial setup:
ls -l/path/to/your/file
drwxwr-x 1 root root 1234 May 20 2024 /path/to/your/file
  • Change ownership:
sudo chown www-data:www-data test

This command changes the owner and group of w3wiki.html to Apache.

  • Verify ownership
ls -la /test

Output:

The ownership of w3wiki.html changes from root:root to apache:apache.

change ownership

Using chown with Recursive Option

This approach is used when you need to change ownership of an entire directory and its contents.

Steps:

1. Open the Terminal: Access your server’s terminal through SSH or directly.

2. Navigate to the Directory: Use the cd command to navigate to the directory containing the files and subdirectories you want to change ownership for

cd /path/to/directory

3. Change Ownership Recursively: Use the chown(change ownership) command with the -R option to change ownership of all files and directories within the specified directory.

sudo chown -R www-data:www-data directory_name

-R stands for recursive, which means the command will be applied to all files and directories within the specified directory.

directory_name : the name of the directory you want to change ownership for.

Example:

  • Initial setup:
ll test/
total 8
drwrwx-x 1 www-data www-data 1234 May 20 2024
drwxr-xr-x 2 root root 4096 May 20 2024
  • Change ownership:
sudo chown -R www-data:www-data test
  • Verify ownership:
ls -la /test

Output:

change ownership

The ownership of the directory /var/www/html/website and all its contents changes from root:root to apache:apache.